File list() in Java

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

Syntax:

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

This method returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.

Note: If this abstract pathname does not denote a directory, then this method returns null. Otherwise, an array of strings is returned, one for each file or directory in the directory.

Parameters: NA

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;

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

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

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

Output:

null


Approach 2: When the files are present.

Java

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

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

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

        System.out.println(Arrays.toString(file.list()));
    }
}

Output:

[1229087091253901]




No comments:

Post a Comment