listFiles(FilenameFilter): This method is available in the java.io.File class of Java.
Syntax:
File[] java.io.File.listFiles(FilenameFilter filter)
This method takes one argument. This method returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfies the specified filter.
Parameters: One parameter is required for this method.
filter: A filename filter.
Returns: An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname.
Note: 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.
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(String) method denies read access to the directory.
Approach 1: When the file is not a directory.
Java
import java.io.File;import java.io.FilenameFilter;public class FilelistFiles3 {public static void main(String[] args) {String pathname = "D:\\hello.txt";File file = new File(pathname);FilenameFilter filter = new FilenameFilter() {@Overridepublic boolean accept(File dir, String name) {// TODO Auto-generated method stubreturn true;}};System.out.println(file.listFiles(filter));}}
Output:
null
Approach 2: When the file is a directory.
Java
import java.io.File;import java.io.FilenameFilter;import java.util.Arrays;public class FilelistFiles3 {public static void main(String[] args) {String pathname = "D:\\report";File file = new File(pathname);FilenameFilter filter = new FilenameFilter() {@Overridepublic boolean accept(File dir, String name) {// TODO Auto-generated method stubreturn true;}};System.out.println(Arrays.toString(file.listFiles(filter)));}}
Output:
No comments:
Post a Comment