Java - Read all .txt files in folder

test picture test · May 7, 2011 · Viewed 70.1k times · Source

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)?

Answer

Andrew White picture Andrew White · May 8, 2011

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 */
  } 
}