Problem:
How to list files in Java? In this post we’re going to show how to use File class to list files and do name filtering using FilenameFilter.
Solution:
In the following example we’re going to list files in a directory. If the program is run without any arguments then it list all files in the current directory (“.”). When only one argument is given it is treated as a path of directory to list. If you provide the second argument it is assumed to be a RegExp pattern of files to show.
package com.farenda.java.io; import java.io.File; import java.io.FilenameFilter; import java.util.Arrays; import java.util.regex.Pattern; public class FileListFilesExample { private static class RegExpFilter implements FilenameFilter { private final Pattern pattern; public RegExpFilter(String pattern) { this.pattern = Pattern.compile(pattern); } @Override public final boolean accept(File file, String name) { return pattern.matcher(name).matches(); } } // The first arg is dir, the second one (if any) files pattern. public static void main(final String[] args) { File dir = selectDirectory(args); String[] names = getFileNames(dir, args); System.out.println("Files and directories in " + dir.getAbsolutePath()); for (String file : names) { System.out.println(file); } } private static File selectDirectory(String[] args) { // current or given as program param return (args.length == 0) ? new File(".") : new File(args[0]); } private static String[] getFileNames(File dir, String[] args) { String[] names; if (args.length > 1) { names = dir.list(new RegExpFilter(args[1])); } else { names = dir.list(); } // Sort just for better readability Arrays.sort(names); return names; } }
As you can see there are two methods to list files: File.list() and File.list(FilenameFilter). The first one just list all files, but the second one takes java.io.FilenameFilter as its parameter and shows only the names for which accept(File file, String name) method returned true.
Let’s see the code in action!
List all files in “/boot” directory:
$> java -classpath /out com.farenda.java.io.FileListFilesExample /boot Files and directories in /boot System.map-4.2.0-27-generic abi-4.2.0-27-generic config-4.2.0-27-generic grub initrd.img-4.2.0-27-generic memtest86+.bin memtest86+.elf memtest86+_multiboot.bin vmlinuz-4.2.0-27-generic
List all files in “/etc” directory that start with pass string:
$> java -classpath /out com.farenda.java.io.FileListFilesExample /etc pass.* Files and directories in /etc passwd passwd-