File listFiles(FileFilter) in Java

listFiles(FileFilter): This method is available in the java.io.File class of Java.

Syntax:

File[] java.io.File.listFiles(FileFilter 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 file 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 does not denote a directory.

Java

import java.io.File;
import java.io.FileFilter;

public class FilelistFiles2 {
    public static void main(String[] args) {

        String pathname = "D:\\hello.txt";
        File file = new File(pathname);

        FileFilter filter = new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                // TODO Auto-generated method stub
                return true;
            }
        };

        System.out.println(file.listFiles(filter));
    }
}

Output:

null


Approach 2: When the file denotes a directory.

Java

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;

public class FilelistFiles2 {
    public static void main(String[] args) {

        String pathname = "D:\\report";
        File file = new File(pathname);

        FileFilter filter = new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                // TODO Auto-generated method stub
                return true;
            }
        };

        System.out.println(Arrays.toString(
file.listFiles(filter)));
    }
}

Output:

[D:\report\1229087091253901]


No comments:

Post a Comment