Tuesday, 22 August 2017

How to read all files in a folder from Java?





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


Answer



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 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.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...