- How to list all files in a directory in Java
- You might also like.
- Read All Files of a Folder in Java
- How to Read All the Files of a Folder in Java
- Read All Files of a Folder Using Files Class in Java
- Read All Files From a Folder Using newDirectoryStream() Method in Java
- Read All Files of a Folder Using the walkFileTree() Method in Java
- Related Article — Java File
- Related Article — Java IO
- Tech Tutorials
- Tuesday, February 28, 2023
- Read or List All Files in a Folder in Java
- Java Example to read all the files in a folder recursively
How to list all files in a directory in Java
In Java, there are many ways to list all files and folders in a directory. You can use either the Files.walk() , Files.list() , or File.listFiles() method to iterate over all the files available in a certain directory.
The Files.walk() is another static method from the NIO API to list all files and sub-directories in a directory. This method throws a NoSuchFileException exception if the folder doesn’t exist. Here is an example that lists all files and sub-directories in a directory called ~/java-runner :
try (StreamPath> paths = Files.walk(Paths.get("~/java-runner"))) // print all files and folders paths.forEach(System.out::println); > catch (IOException ex) ex.printStackTrace(); >
Since it returns a Stream object, you can filter out nested directories and only list regular files like below:
try (StreamPath> paths = Files.walk(Paths.get("~/java-runner"))) // filer out sub-directories ListString> files = paths.filter(x -> Files.isRegularFile(x)) .map(Path::toString) .collect(Collectors.toList()); // print all files files.forEach(System.out::println); > catch (IOException ex) ex.printStackTrace(); >
try (StreamPath> paths = Files.walk(Paths.get("~/java-runner"))) // filer out regular files ListString> folders = paths.filter(x -> Files.isDirectory(x)) .map(Path::toString) .collect(Collectors.toList()); // print all folders folders.forEach(System.out::println); > catch (IOException ex) ex.printStackTrace(); >
try (StreamPath> paths = Files.walk(Paths.get("~/java-runner"))) // keep only `.java` files ListString> javaFiles = paths.map(Path::toString) .filter(x -> x.endsWith(".java")) .collect(Collectors.toList()); // print all files javaFiles.forEach(System.out::println); > catch (IOException ex) ex.printStackTrace(); >
By default, the Stream object returned by Files.walk() recursively walks through the file tree up to an n-level (all nested files and folders). However, you can pass another parameter to Files.walk() to limit the maximum number of directory levels to visit. Here is an example that restricts the directory level to a top-level folder only (level 1):
try (StreamPath> paths = Files.walk(Paths.get("~/java-runner"), 1)) // print all files and folders in the current folder paths.forEach(System.out::println); > catch (IOException ex) ex.printStackTrace(); >
In the above code, the second parameter of Fils.walk() is the maximum number of levels of directories to visit. A value of 0 means that only the starting file is visited, unless denied by the security manager. A value of Integer.MAX_VALUE indicatea that all levels should be traversed.
The Files.list() static method from NIO API provides the simplest way to list the names of all files and folders in a given directory:
try (StreamPath> paths = Files.list(Paths.get("~/java-runner"))) // print all files and folders paths.forEach(System.out::println); > catch (IOException ex) ex.printStackTrace(); >
The Files.list() method returns a lazily populated Stream of entries in the directory. So you can apply all the above filters for Files.walk() on the stream.
In old Java versions (JDK 6 and below), the File.listFiles() method is available to list all files and nested folders in a directory. Here is an example that uses File.listFiles() to print all files and folders in the given directory:
File folder = new File("~/java-runner"); // list all files for (File file : folder.listFiles()) System.out.println(file); >
File folder = new File("~/java-runner"); // list all regular files for (File file : folder.listFiles()) if (file.isFile()) System.out.println(file); > >
File folder = new File("~/java-runner"); // list all sub-directories for (File file : folder.listFiles()) if (file.isDirectory()) System.out.println(file); > >
public void listFilesRecursive(File folder) for (final File file : folder.listFiles()) if (file.isDirectory()) // uncomment this to list folders too // System.out.println(file); listFilesRecursive(file); > else System.out.println(file); > > > // list files recursively File folder = new File("~/java-runner"); listFilesRecursive(folder);
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
Read All Files of a Folder in Java
- How to Read All the Files of a Folder in Java
- Read All Files of a Folder Using Files Class in Java
- Read All Files From a Folder Using newDirectoryStream() Method in Java
- Read All Files of a Folder Using the walkFileTree() Method in Java
This tutorial introduces how to read all the files of a folder in Java and lists some example codes to understand it.
There are several ways to get all the files of a folder. Here we could use File , Files and DirectoryStream classes, and many more. Let’s see the examples.
How to Read All the Files of a Folder in Java
Here, we use the File class to collect all the files and folder in the source directory and then use the isDirectory() method to check whether it is a file or folder. See the example below.
import java.io.File; import java.text.ParseException; public class SimpleTesting public static void findAllFilesInFolder(File folder) for (File file : folder.listFiles()) if (!file.isDirectory()) System.out.println(file.getName()); > else findAllFilesInFolder(file); > > > public static void main(String[] args) throws ParseException File folder = new File("/home/folder/src"); findAllFilesInFolder(folder); > >
Read All Files of a Folder Using Files Class in Java
If you want to use stream, use the walk() method of Files class that returns a Path’s stream . After that, we use the filter() method to collect files only and use forEach() to print them.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; public class SimpleTesting public static void main(String[] args) throws IOException try (StreamPath> paths = Files.walk(Paths.get("/home/folder/src"))) paths .filter(Files::isRegularFile) .forEach(System.out::println); > > >
Read All Files From a Folder Using newDirectoryStream() Method in Java
Here, we use the Files class and its newDirectoryStream() method that returns a stream of Path . After that, we use a for-each loop to iterate the list of files and print the file name.
import java.io.IOException; import java.nio.file.DirectoryIteratorException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class SimpleTesting public static void main(String[] args) throws IOException try (DirectoryStreamPath> stream = Files.newDirectoryStream(Paths.get("/home/folder/src/"))) for (Path file: stream) System.out.println(file.getFileName()); > > catch (IOException | DirectoryIteratorException ex) System.err.println(ex); > > >
Read All Files of a Folder Using the walkFileTree() Method in Java
Here, we use the walkFileTree() method of the Files class that takes two arguments: the source folder and the SimpleFileVisitor reference. See the example below.
import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; public class SimpleTesting public static void main(String[] args) throws IOException SimpleFileVisitorPath> file = new SimpleFileVisitorPath>() @Override public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) throws IOException System.out.println(filePath); return FileVisitResult.CONTINUE; > >; Files.walkFileTree(Paths.get("/home/folder/src"), file); > >
Related Article — Java File
Related Article — Java IO
Tech Tutorials
Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.
Tuesday, February 28, 2023
Read or List All Files in a Folder in Java
In this post we’ll see how to read or list all the files in a directory using Java. Suppose you have folder with files in it and there are sub-folders with files in those sub-folders and you want to read or list all the files in the folder recursively.
Here is a folder structure used in this post to read the files. Test, Test1 and Test2 are directories here and then you have files with in those directories.
Test abc.txt Test1 test.txt test1.txt Test2 xyz.txt
Java Example to read all the files in a folder recursively
There are two ways to list all the files in a folder; one is using the listFiles() method of the File class which is there in Java from 1.2.
Another way to list all the files in a folder is to use Files.walk() method which is a recent addition in Java 8.
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Stream; public class ListFiles < public static void main(String[] args) < File folder = new File("G:\\Test"); ListFiles listFiles = new ListFiles(); System.out.println("reading files before Java8 - Using listFiles() method"); listFiles.listAllFiles(folder); System.out.println("-------------------------------------------------"); System.out.println("reading files Java8 - Using Files.walk() method"); listFiles.listAllFiles("G:\\Test"); >// Uses listFiles method public void listAllFiles(File folder)< System.out.println("In listAllfiles(File) method"); File[] fileNames = folder.listFiles(); for(File file : fileNames)< // if directory call the same method again if(file.isDirectory())< listAllFiles(file); >else < try < readContent(file); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> > > // Uses Files.walk method public void listAllFiles(String path) < System.out.println("In listAllfiles(String path) method"); try(Streampaths = Files.walk(Paths.get(path))) < paths.forEach(filePath -> < if (Files.isRegularFile(filePath)) < try < readContent(filePath); >catch (Exception e) < // TODO Auto-generated catch block e.printStackTrace(); >> >); > catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> public void readContent(File file) throws IOException < System.out.println("read file " + file.getCanonicalPath() ); try(BufferedReader br = new BufferedReader(new FileReader(file)))< String strLine; // Read lines from the file, returns null when end of stream // is reached while((strLine = br.readLine()) != null)< System.out.println("Line is - " + strLine); >> > public void readContent(Path filePath) throws IOException < System.out.println("read file " + filePath); ListfileList = Files.readAllLines(filePath); System.out.println("" + fileList); > >
reading files before Java8 - Using listFiles() method In listAllfiles(File) method read file G:\Test\abc.txt Line is - This file is in Test folder. In listAllfiles(File) method read file G:\Test\Test1\test.txt Line is - This file test is under Test1 folder. read file G:\Test\Test1\test1.txt Line is - This file test1 is under Test1 folder. In listAllfiles(File) method read file G:\Test\Test2\xyz.txt Line is - This file xyz is under Test2 folder. ------------------------------------------------- reading files Java8 - Using Files.walk() method In listAllfiles(String path) method read file G:\Test\abc.txt [This file is in Test folder.] read file G:\Test\Test1\test.txt [This file test is under Test1 folder.] read file G:\Test\Test1\test1.txt [This file test1 is under Test1 folder.] read file G:\Test\Test2\xyz.txt [This file xyz is under Test2 folder.]
Here we have two overloaded listAllFiles() methods. First one takes File instance as argument and use that instance to read files using the File.listFiles() method. In that method while going through the list of files under a folder you check if the next element of the list is a file or a folder. If it is a folder then you recursively call the listAllFiles() method with that folder name. If it is a file you call the readContent() method to read the file using BufferedReader.
Another version of listAllFiles() method takes String as argument. In this method whole folder tree is traversed using the Files.walk() method. Here again you verify if it is a regular file then you call the readContent() method to read the file.
Note that readContent() method is also overloaded one takes File instance as argument and another Path instance as argument.
If you just want to list the files and sub-directories with in the directory then you can comment the readContent() method.
That’s all for this topic Read or List All Files in a Folder in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!