How to read all files in a folder from Java?

How to read all the files in a folder through Java?


Solution 1:

public void listFilesForFolder(final File folder) {
    for (final File fileEntry : folder.listFiles()) {
        if (fileEntry.isDirectory()) {
            listFilesForFolder(fileEntry);
        } else {
            System.out.println(fileEntry.getName());
        }
    }
}

final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);

Files.walk API is available from Java 8.

try (Stream<Path> paths = Files.walk(Paths.get("/home/you/Desktop"))) {
    paths
        .filter(Files::isRegularFile)
        .forEach(System.out::println);
} 

The example uses try-with-resources pattern recommended in API guide. It ensures that no matter circumstances the stream will be closed.

Solution 2:

File folder = new File("/Users/you/folder/");
File[] listOfFiles = folder.listFiles();

for (File file : listOfFiles) {
    if (file.isFile()) {
        System.out.println(file.getName());
    }
}

Solution 3:

In Java 8 you can do this

Files.walk(Paths.get("/path/to/folder"))
     .filter(Files::isRegularFile)
     .forEach(System.out::println);

which will print all files in a folder while excluding all directories. If you need a list, the following will do:

Files.walk(Paths.get("/path/to/folder"))
     .filter(Files::isRegularFile)
     .collect(Collectors.toList())

If you want to return List<File> instead of List<Path> just map it:

List<File> filesInFolder = Files.walk(Paths.get("/path/to/folder"))
                                .filter(Files::isRegularFile)
                                .map(Path::toFile)
                                .collect(Collectors.toList());

You also need to make sure to close the stream! Otherwise you might run into an exception telling you that too many files are open. Read here for more information.

Solution 4:

All of the answers on this topic that make use of the new Java 8 functions are neglecting to close the stream. The example in the accepted answer should be:

try (Stream<Path> filePathStream=Files.walk(Paths.get("/home/you/Desktop"))) {
    filePathStream.forEach(filePath -> {
        if (Files.isRegularFile(filePath)) {
            System.out.println(filePath);
        }
    });
}

From the javadoc of the Files.walk method:

The returned stream encapsulates one or more DirectoryStreams. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed.

Solution 5:

One remark according to get all files in the directory.
The method Files.walk(path) will return all files by walking the file tree rooted at the given started file.

For instance, there is the next file tree:

\---folder
    |   file1.txt
    |   file2.txt
    |
    \---subfolder
            file3.txt
            file4.txt

Using the java.nio.file.Files.walk(Path):

Files.walk(Paths.get("folder"))
        .filter(Files::isRegularFile)
        .forEach(System.out::println);

Gives the following result:

folder\file1.txt
folder\file2.txt
folder\subfolder\file3.txt
folder\subfolder\file4.txt

To get all files only in the current directory use the java.nio.file.Files.list(Path):

Files.list(Paths.get("folder"))
        .filter(Files::isRegularFile)
        .forEach(System.out::println);

Result:

folder\file1.txt
folder\file2.txt