Get a list of files and folders in a directory with Java

Before Java 8, you can use the listFiles() method of the File class with the parameter of the directory that we want to get the list of files and directories to do this. Eg:

The return result will be a list of File objects containing information about the files and folders in the directory that we want to get the list. You can print the information of these files as follows:

Result:

You can also filter out the list of files and folders if you want!

Another Java class that you can also use to get a list of files and directories is DirectoryStream.

But first, you need the Path object containing the directory information you need to get the list first:

then use the DirectoryStream class as follows:

Result:

From Java 8 onwards, you can use the static list() method of the Files class to do this, specifically as follows:

The returned object of the list() method is a Stream object. You can get a list of names then collect them into a List, then for each List to print out the file name like I’m doing!

The result is the same as above:

Add Comment