Explain Codes LogoExplain Codes Logo

How to read all files in a folder from Java?

java
file-handling
java-nio-file
try-with-resources
Nikita BarsukovbyNikita Barsukov·Nov 7, 2024
TLDR

Use the Files.walk method to traverse directories in Java, which provides a Stream<Path> for the iterative process. Filter only regular files with the Files.isRegularFile predicate in a lambda expression:

Path dir = Paths.get("/your/directory"); try (Stream<Path> paths = Files.walk(dir)) { paths.filter(Files::isRegularFile).forEach(System.out::println); }

Make sure to swap "/your/directory" with your target directory. This concise code piece lists all the files (excluding directories) within the given path.

Exploring options for file traversal

Depending on the depth of traversal you need, there are two main options available with java.nio.file.

Files.walk: The pathfinder for deep traversal

If you're embarking on a journey of artifact recovery deep within your file system archaeology, Files.walk is the Indiana Jones of methods:

int maxDepth = 5; // It's not the size of the depth, it's how you use it! try (Stream<Path> paths = Files.walk(dir, maxDepth)) { paths.filter(Files::isRegularFile).forEach(System.out::println); }

Remember to handle the Cave of Exceptions (aka IOException) brands with grace, and limit your file-system spelunking to a manageable depth.

Files.list: The guardian of the shallow realm

If your adventures don't involve going down rabbit holes, Files.list will stand by you like a devoted squire. It's more efficient for listing your treasure chest (directory):

try (Stream<Path> paths = Files.list(dir)) { paths.filter(Files::isRegularFile).forEach(System.out::println); }

File: The brave knight of the Java Kingdom

Of course, how can anyone forget the gallant File class that paved the early ways of file handling, irrespective of its age, it still stands strong:

File folder = new File("/your/directory"); File[] listOfFiles = folder.listFiles(); // Behold, the artifact list! for (File file : listOfFiles) { if (file.isFile()) { System.out::println(file.getName()); } }

Despite the advent of java.nio.file, the File class remains a viable choice for simple file operations.

Resource and Exception Management: A cautionary tale

Beware, resource leakage monsters lurk!

Always wrap the handling of resources in a try-with-resources to close them properly and keep those thirsty resource leakage monsters at bay:

try (Stream<Path> paths = Files.walk(dir)) { // The intrepid explorer sets on a journey paths.filter(Files::isRegularFile).forEach(System.out::println); // Reading ancient scripts } // The adventure concludes with a safe return home!

The exception beasts don't spare anyone

In the realm of files and directories, the exception beasts are notorious for creating issues. Your code, the hero of the tale, must combat these beasts with agile IOException handling:

try (Stream<Path> stream = Files.walk(dir)) { stream.filter(Files::isRegularFile).forEach(System.out::println); } catch (IOException e) { // Here be dragons! Handle them wisely. e.printStackTrace(); }

Advanced potion brewing: Working with collected results

Brewing a potion of file remembrance

To remember the paths of your epic adventures for later expeditions, brew them into a potion (or List<Path> in Java lingo):

List<Path> fileList; try (Stream<Path> paths = Files.walk(dir)) { fileList = paths.filter(Files::isRegularFile).collect(Collectors.toList()); }

The transmutation spell: Path to File

If you need the old school File objects from Path instances, this transmutation spell will serve you fairly:

List<File> fileObjects = fileList.stream().map(Path::toFile).collect(Collectors.toList());

The Apache's treasure trove: Third-party libraries

Sometimes, the wisdom of ancient tribes (third-party libraries) can guide us to riches:

Apache Commons IO

The wise Apache tribe has shared FileUtils.listFiles, a treasure map guiding to your artifacts effortlessly:

Collection<File> files = FileUtils.listFiles(new File("/your/directory"), null, true); files.forEach(System.out::println);

The FileUtils method brings balance in the chaos with its easy-to-use filtering and recursion handling.