Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read all files in a folder from Java?

How to read all the files in a folder through Java? It doesn't matter which API.

like image 433
M.J. Avatar asked Dec 04 '09 03:12

M.J.


People also ask

How do I read all files in a directory?

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.

What does the files list () method in java do?

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.

Where does java look for files?

The answer is the working folder, which means the folder in which you executed the "java ..." command.


1 Answers

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.

like image 68
rich Avatar answered Sep 19 '22 04:09

rich