1. Introduction
Managing files is a common functionality used in many applications that need to save permanently important data or static resources like images or documents. In this tutorial, we are going to show how to list files in a specific directory using plain Java methods.
2. List files using File.listFiles(...)
To list files from a folder without going deep into sub-directories we can use the Files.listFiles(...)
method:
In this example, we use listFiles(...)
method to print all files from /tmp
folder. The second part of our main
uses the FileFilter
object that we can provide as a listFiles(...)
method parameter. This allows us to filter files and prints only resources with specific extension - .txt
in our case.
3. Print files from directory using DirectoryStream
from Java 7
In Java 7 we have a dedicated stream object called DirectoryStream
for listing files in a directory.
Let's check the example code:
In this example we used Files.newDirectoryStream(...)
method to create new DirectoryStream<Path>
stream. Then we iterate over each item in the stream and print filenames but only for files: Files.isDirectory(...)
.
4. List files from a folder using Files.walk(...)
method
We can list files from directory using Files.walk
method that allows us to navigate over folder structure:
To make sure that JDK will close the resource we used try-with-resources
syntax. In this example first, we created stream Stream<path>
using Files.walk
method. Then we retrieved the necessary value from our complex object.
5. Conclusion
In this article, we presented several methods to list files in a directory using Java. There are several ways to achieve that, choose the one that is the best for you.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}