- Java File IO List files and directories Example
- Java Directory Listing Code Example 1 :
- Java Directory Listing Code Example 2:
- Java Directory Listing Code Example 3:
- Java Directory Listing Code Example 4 :
- Related File IO Tutorials:
- Other Java File IO Tutorials:
- About the Author:
- How to list all files in a directory in Java
- You might also like.
- How to list all files in a directory in Java
- You might also like.
Java File IO List files and directories Example
In Java, to query a list of files and directories in a specific directory, we use the File class under java.io package and follow these steps:
File dir = new File(“C:/Path/To/My/Directory”);
-
- Use one of the following methods of the File class:
-
-
- String[] list()
- String[] list(FilenameFilter filter)
- File[] listFiles()
- File[] listFiles(FileFilter filter)
- File[] list(FilenameFilter filter)
-
- If you just want to get names of the files and directories, use the methods that return an array of Strings, the list() methods (method 1 and 2).
- If you want to get a list of File objects in order to do something with the files, then go with the methods that return an array of File object, the listFiles() methods (method 3, 4 and 5).
- If you want to list all files and directories in the specified directory, use the no-argument methods (method 1 and 3)
- If you don’t want to list all files and directories, but some kind of files based on some conditions, then go with the methods that accept a FilenameFilter or FileFilter as an argument (method 2, 4, and 5). Then you have to create a class that implements either the interface FilenameFilter or FileFilter, and override their methods accept(File dir, String name) or accept(File pathname) , respectively.
-
- The list() methods return an array of Strings.
- The listFiles() methods return an array of File objects.
- The non-argument methods list everything under the directory.
- The argument-based methods list only files and directories which satisfy the filter you provided.
Java Directory Listing Code Example 1 :
String dirPath = "g:/Music/English"; File dir = new File(dirPath); String[] files = dir.list(); if (files.length == 0) < System.out.println("The directory is empty"); >else < for (String aFile : files) < System.out.println(aFile); >>
This example uses String[] list() method to get names of files and directories just as Strings, and you can’t do anything further with the files/directories.
Java Directory Listing Code Example 2:
String dirPath = "g:/Music/English"; File dir = new File(dirPath); File[] files = dir.listFiles(); if (files.length == 0) < System.out.println("The directory is empty"); >else < for (File aFile : files) < System.out.println(aFile.getName() + " - " + aFile.length()); >>
This example uses File[] listFiles() method to retrieve an array of File objects, so you can do something more with an individual file or directory, such as getting absolute path or file size.
Java Directory Listing Code Example 3:
Suppose we want to list only MP3 files, create a local class that implements the interface FilenameFilter , and overrides the accept(File file, String name) method as follows:
FilenameFilter mp3Filter = new FilenameFilter() < public boolean accept(File file, String name) < if (name.endsWith(".mp3")) < // filters files whose extension is .mp3 return true; >else < return false; >> >;
If the accept() method returns true, the file will be listed. Then call the method listFiles(FilenameFilter filter) as follows:
String dirPath = "g:/Music/English"; File dir = new File(dirPath); File[] files = dir.listFiles(mp3Filter); if (files.length == 0) < System.out.println("There is no MP3 files"); >else < for (File aFile : files) < System.out.println(aFile.getName() + " - " + aFile.length()); >>
Note: as the name suggests, the FilenameFilter interface is for filtering file names only. If you want to filter other file’s properties such as size or modification time, use the method listFiles(FileFilter filter)
Java Directory Listing Code Example 4 :
Suppose you want to list only the files whose size is greater than 3MB, create a local class that implements the interface FileFilter , and overrides the accept(File file) method as follows:
FileFilter sizeFilter = new FileFilter() < public boolean accept(File file) < if (file.isFile() && file.length() >3*1024*1024) < // filters files whose size greater than 3MB return true; >else < return false; >> >;
Then call the method listFiles(FileFilter filter) as follows:
String dirPath = "g:/Music/English"; File dir = new File(dirPath); File[] files = dir.listFiles(sizeFilter); if (files.length == 0) < System.out.println("There is no files bigger than 3MB"); >else < for (File aFile : files) < System.out.println(aFile.getName() + " - " + aFile.length()); >>
Related File IO Tutorials:
Other Java File IO Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.
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.
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.
-