How to read all files in a folder from Java? How to read all files in a folder from Java? java java

How to read all files in a folder from Java?


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.


File folder = new File("/Users/you/folder/");File[] listOfFiles = folder.listFiles();for (File file : listOfFiles) {    if (file.isFile()) {        System.out.println(file.getName());    }}


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.