java.io.File listFiles(FilenameFilter filter)
Description
Throws:
SecurityException – If a security manager exists and its SecurityManager.checkRead(String) method denies read access to the directory.
Method Syntax
public File[] listFiles(FilenameFilter filter)
Method Argument
Data Type | Parameter | Description |
---|---|---|
FilenameFilter | filter | A filename filter |
Method Returns
This method returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
Compatibility
Requires Java 1.2 and up
Java File listFiles(FilenameFilter filter) Example
Below is a java code demonstrates the use of listFiles(FilenameFilter filter) method of File class. The example presented might be simple however it shows the behaviour of the listFiles(FilenameFilter filter) method of File class. Because the listFiles(FilenameFilter filter) method returns an array of String the denotes the filenames inside the directory if and only if the abstract pathname denotes directory, thus we have first put a check if the file is a directory or not. It wouldn’t make sense to just blindly list down the filenames without making sure that the pathname is a directory because the returned value would be null. Make sure to have it checked out to avoid unnecessary issues in using this method.The filter that we have used is to list down all files and directories that starts with string “test”.
package com.javatutorialhq.java.examples; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; /* * This example source code demonstrates the use of * listFiles(FilenameFilter filter) method of File class. * */ public class FileListFilesFilenameFilterExample { public static void main(String[] args) { // initialize File object File file = new File("C:javatutorialhq"); // check if the specified pathname is directory first if(file.isDirectory()){ //list all files on directory File[] files = file.listFiles(new FilenameFilter() { //apply a filter @Override public boolean accept(File dir, String name) { boolean result; if(name.startsWith("test")){ result=true; } else{ result=false; } return result; } }); //print all files on the directory for(File f:files){ try { System.out.println(f.getCanonicalPath()); } catch (IOException e) { e.printStackTrace(); } } } } }