File list(FilenameFilter) in Java

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

Syntax:

String[] java.io.File.list(FilenameFilter filter)

This method takes one argument. This method returns an array of strings naming 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 strings naming the files and directories in the directory denoted by this abstract pathname that was accepted by the given filter. The array will be empty if the directory is empty or if no names were accepted by the filter.

Note: 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 files are not present.

Java

import java.io.File;
import java.io.FilenameFilter;

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

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

        FilenameFilter filer = new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                // TODO Auto-generated method stub
                return false;
            }
        };

        System.out.println(file.list(filer));
    }
}

Output:

null


Approach 2; When the files are present

Java

import java.io.File;
import java.io.FilenameFilter;

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

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

        FilenameFilter filer = new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                // TODO Auto-generated method stub
                return false;
            }
        };

        System.out.println(file.list(filer));
    }
}

Output:

[Ljava.lang.String;@4361bd48


No comments:

Post a Comment