Java - Read all .txt files in folder

后端 未结 7 1882
醉话见心
醉话见心 2020-12-08 15:49

Let\'s say, I have a folder called maps and inside maps I have map1.txt, map2.txt, and map3.txt. How can I u

7条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 16:06

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

提交回复
热议问题