Java - Read all .txt files in folder

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

    With NIO you can do the following:

    Files.walk(Paths.get("/path/to/files"))
              .filter(Files::isRegularFile)
              .filter(path -> path.getFileName().toString().endsWith(".txt"))
              .map(FileUtils::readFileToString)
              // do something
    

    To read the file contents you may use Files#readString but, as usual, you need to handle IOException inside lambda expression.

提交回复
热议问题