Explain Codes LogoExplain Codes Logo

Getting the filenames of all files in a folder

java
file-management
file-system
java-8
Nikita BarsukovbyNikita Barsukov·Jan 6, 2025
TLDR

To get a quick list of all filenames in a directory, try this neat Java one-liner:

new File("/path/to/folder").listFiles(file -> file.isFile()).forEach(file -> System.out.println(file.getName()));

This nugget uses the File's listFiles method combined with a lambda expression to filter out directories and print out the names of "actual files". Simple, ain't it?

Decoding the one-liner

Let's demystify each component of the one-liner we just used:

  • new File("/path/to/folder"): Creates a File instance pointing to the target directory.
  • listFiles(file -> file.isFile()): Filters out directories, ensuring we only deal with genuine files.
  • forEach(file -> ...): Executes the lambda function for each file.
  • file.getName(): Retrieves the filename, excluding the full file path.

This guarantees only actual files, excluding subdirectories, are considered.

Cross-platform compatibility

File path syntax varies across operating systems. Java does a commendable job at abstracting these concerns, nonetheless, make sure your file paths reflect the correct syntax according to your OS (Windows uses backslashes, UNIX uses forward slashes).

Advanced filtering with FileFilter and FilenameFilter

When you need to get specific with your filtering, Java has you covered with FileFilter and FilenameFilter interfaces:

File dir = new File("/path/to/folder"); File[] javaFiles = dir.listFiles((directory, fileName) -> fileName.endsWith(".java")); // Only selecting the Java masterpieces

The above example filters the files in the directory, keeping only *.java files because, you know, Java is the new black!

Wrangling filenames with ArrayList

Sometimes, you might fancy doing more than just printing out the filenames. An ArrayList<String> can wake up the tweaker in you:

File[] files = new File("/path/to/folder").listFiles(File::isFile); List<String> fileNames = Arrays.stream(files) .map(File::getName) // Return filename, because full paths are like telling your whole life story .collect(Collectors.toList());

With this list, you can now play around with your filenames, spin them, flip them, or rearrange them - your call.

Additional cool tricks with File class

File path constructors

The File class in Java is fairly flexible with how you can specify the file paths. For instance, you can breadcrumb your file path constructors like ‘new File(parent, child)`. This construct helps maintain file paths readability and cross-platform compatibility.

Is it a bird, is it a plane, is it a file?

When you're hunting for files, be sure you're dealing with real files and not directories in disguise. isFile() will sort the posers from the actual files.

Taking care of exceptions

I/O operations can be trippy, so don't forget to handle your FileNotFoundException or IOException. Robust error management results in happy, undisturbed users.

Exploring ... even beyond

Apache Commons IO or Google's Guava libraries extend the ordinary Java capabilities providing even more powerful and succinct ways for listing and filtering files.

Trekking through the file tree

With Files.walkFileTree, your directories are no more a blackhole. This method allows you to perform operations on each file or directory within a directory tree. Traverse, young Padawan!