List files in a directory in Java

List files in a directory in Java

List files using File.listFiles()

You can use File.listFiles() method to list files in a directory. listFiles method can take a FileFilter as an argument and returns an array of files.

1
2
3
4
5
6
File file = new File("/path/to/directory");
for (File f : file.listFiles(File::isFile)){
if(f.isFile()){
log.info(f.getAbsolutePath());
}
}

List files using Files.walk()

Also, you can use Files.walk() method to list files in a directory. Files.walk() method returns a Stream which you can filter by Files.isRegularFile() method. walk() method will walk the directory tree and return all files in the directory and its subdirectories.

1
2
3
4
5
6
7
   Path path = Paths.get("/path/to/directory");
try (Stream<Path> paths = Files.walk(path)) {
List<Path> filePaths = paths.filter(Files::isRegularFile).toList();
for (Path p : filePaths){
log.info(p.toString());
}
}

List files in classpath

If you want to list files in the classpath, you can use the following code snippet:

1
2
3
4
5
6
7
8
9
URL url = this.getClass().getClassLoader().getResource("directory");
if (url != null) {
File file = new File(url.getFile());
for (File f : file.listFiles(File::isFile)){
if(f.isFile()){
log.info(f.getAbsolutePath());
}
}
}

If you are using Spring, you can use ResourceUtils class to get the file from the classpath:

1
2
3
4
5
6
File file = ResourceUtils.getFile("classpath:directory");
for (File f : file.listFiles(File::isFile)){
if(f.isFile()){
log.info(f.getAbsolutePath());
}
}