Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Read all .txt files in folder

Tags:

Let's say, I have a folder called maps and inside maps I have map1.txt, map2.txt, and map3.txt. How can I use Java and the BufferReader to read all of the .txt files in folder maps (if it is at all possible)?

like image 424
test Avatar asked May 07 '11 21:05

test


2 Answers

Something like the following should get you going, note that I use apache commons FileUtils instead of messing with buffers and streams for simplicity...

File folder = new File("/path/to/files");
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
  File file = listOfFiles[i];
  if (file.isFile() && file.getName().endsWith(".txt")) {
    String content = FileUtils.readFileToString(file);
    /* do somthing with content */
  } 
}
like image 183
Andrew White Avatar answered Oct 18 '22 02:10

Andrew White


I would take @Andrew White answer (+1 BTW) one step further, and suggest you would use FileNameFilter to list only relevant files:

FilenameFilter filter = new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.endsWith(".txt");
    }
};

File folder = new File("/path/to/files");
File[] listOfFiles = folder.listFiles(filter);

for (int i = 0; i < listOfFiles.length; i++) {
    File file = listOfFiles[i];
    String content = FileUtils.readFileToString(file);
    // do something with the file
}
like image 29
MByD Avatar answered Oct 18 '22 04:10

MByD