listFiles(): This method is available in the java.io.File class of Java.
Syntax:
File[] java.io.File.listFiles()
This method returns an array of abstract pathnames denoting the files 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 File objects is returned, one for each file or directory in the directory.
Parameters: NA
Returns: An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. 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 files are present in the directory.
Java
import java.io.File;import java.util.Arrays;public class FilelistFiles {public static void main(String[] args) {String pathname = "D:\\report";File file = new File(pathname);System.out.println(Arrays.toString(file.listFiles()));}}
Output:
[D:\report\1229087091253901]
Approach 2: When the files are not present in the directory.
Java
import java.io.File;import java.util.Arrays;public class FilelistFiles {public static void main(String[] args) {String pathname = "D:\\hello.txt";File file = new File(pathname);System.out.println(Arrays.toString(file.listFiles()));}}
Output
null
No comments:
Post a Comment