java.io.File list(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 String[] list(FilenameFilter filter)
Method Argument
Data Type | Parameter | Description |
---|---|---|
FilenameFilter | filter | A filename filter |
Method Returns
This method returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that were accepted by the given filter. The array will be empty if the directory is empty or if no names were accepted by the filter. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
Compatibility
Requires Java 1.0 and up
Java File list(FilenameFilter filter) Example
Below is a java code demonstrates the use of list(FilenameFilter filter) method of File class. The example presented might be simple however it shows the behaviour of the list(FilenameFilter filter) method of File class. Because the list(FilenameFilter filter) method returns an array of String filtered depending on the FilenameFilter as method argument, it is imperative that the abstract pathname is a directory. As such we have put a check isDirectory() to make sure that the pathname is a directory or not before proceeding with the operation.
package com.javatutorialhq.java.examples; import java.io.File; import java.io.FilenameFilter; /* * This example source code demonstrates the use of * list(FilenameFilter filter) method of File class. * */ public class FileListFilenameFilterExample { public static void main(String[] args) { // initialize File object File file = new File("C:javatutorialhqinput"); // check if the specified pathname is directory first if(file.isDirectory()){ //list specified files on the specified directory String[] files = file.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { boolean value; // return files only that begins with test if(name.startsWith("test")){ value=true; } else{ value=false; } return value; } }); for(String s:files){ System.out.println(s); } } } }