Java - Read all .txt files in folder

2020-02-02 18:23发布

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

7条回答
smile是对你的礼貌
2楼-- · 2020-02-02 18:55

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.

查看更多
Summer. ? 凉城
3楼-- · 2020-02-02 19:03

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 */
  } 
}
查看更多
老娘就宠你
4楼-- · 2020-02-02 19:08

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
}
查看更多
时光不老,我们不散
5楼-- · 2020-02-02 19:13

Using only JDK, If all your files are in one directory:

File dir = new File("path/to/files/");

for (File file : dir.listFiles()) {
    Scanner s = new Scanner(file);
    // do something with file
    s.close();
}

To exclude files, you can use listFiles(FileFilter)

查看更多
ら.Afraid
6楼-- · 2020-02-02 19:14

If you want a better way of doing this using the new java.nio api, then this is the way, taken from the java docs

Path dir = ...;
try (DirectoryStream<Path> stream =
     Files.newDirectoryStream(dir, "*.txt")) {
    for (Path entry: stream) {
        System.out.println(entry.getFileName());
    }
} catch (IOException x) {
    // IOException can never be thrown by the iteration.
    // In this snippet, it can // only be thrown by newDirectoryStream.
    System.err.println(x);
}
查看更多
爷、活的狠高调
7楼-- · 2020-02-02 19:15
    final File folder = new File("C:/Dev Tools/apache-tomcat-6.0.37/webapps/ROOT/somefile");
    for (final File fileEntry : folder.listFiles()) {
           System.out.println("FileEntry Directory "+fileEntry);
查看更多
登录 后发表回答