Java - Read all .txt files in folder

后端 未结 7 1884
醉话见心
醉话见心 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:24

    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
    }
    

提交回复
热议问题