Managing files is 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
To list files from a folder without going deep into sub-directories we can use
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
3. Print files from directory using
DirectoryStream from Java 7
In Java 7 we have a dedicated stream object:
DirectoryStream for listing files in a directory.
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:
4. List files from a folder using
We can list files from directory using
To make sure that
div will close the resource we used
try-with-resources syntax. First, we create stream
Files.walk method. Then we retrieve the necessary value from our complex object.
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.