Java Program to print the file content for the file names starting with "Test-".
package fileio;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
public class PrintFileContent {
public static void main(String[] args) {
try {
final String filePrefix = "Test-";
String filesDir = System.getProperty("user.dir")+"\\src\\fileio";
File dir = new File(filesDir);
File[] foundFiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(filePrefix);
}
});
System.out.println("Number of files found : "+foundFiles.length);
System.out.println("");
for (File file : foundFiles) {
System.out.println("----------------------------------------------");
System.out.println(" "+file.getName());
//Prints the file content.
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(file));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Note:
File "Test-001.txt","Test-002.txt" and "Test-003.txt" should have some content
Ex: "This content of test file for Test001"
Executing the above java program:
Output:
package fileio;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
public class PrintFileContent {
public static void main(String[] args) {
try {
final String filePrefix = "Test-";
String filesDir = System.getProperty("user.dir")+"\\src\\fileio";
File dir = new File(filesDir);
File[] foundFiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(filePrefix);
}
});
System.out.println("Number of files found : "+foundFiles.length);
System.out.println("");
for (File file : foundFiles) {
System.out.println("----------------------------------------------");
System.out.println(" "+file.getName());
//Prints the file content.
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(file));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Note:
File "Test-001.txt","Test-002.txt" and "Test-003.txt" should have some content
Ex: "This content of test file for Test001"
Executing the above java program:
Output:
No comments:
Post a Comment