How to read all the files in a folder through Java? It doesn't matter which API.
The listdir() function inside the os module is used to list all the files inside a specified directory. This function takes the specified directory path as an input parameter and returns the names of all the files inside that directory. We can iterate through all the files inside a specific directory using the os.
list() returns the array of files and directories in the directory defined by this abstract path name. The method returns null, if the abstract pathname does not denote a directory.
The answer is the working folder, which means the folder in which you executed the "java ..." command.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With