In this tutorial, we will learn how to list all the files and sub-directories present inside a directory.
The "list()" method of the Java File class is used to list all the files and sub-directories present inside a directory. It returns all the files and directories as a string array.
Example: List all files using list() method
import java.io.File;class Main {public static void main(String[] args) {// creates a file objectFile file = new File("C:\\Users\\Guest User\\Desktop\\Java File\\List Method");// returns an array of all filesString[] fileList = file.list();for(String str : fileList) {System.out.println(str);}}}
Output
.vscodefile.txtdirectorynewFile.txt
In the above example, we have created a file object named file. The object holds information about the specified path.
File file = new File("C:\\Users\\Guest User\\Desktop\\Java File\\List Method");
We have used the "list()" method to list all the files and sub-directories present in the specified path.
file.list();
Note: We have used double-backslash while specifying the path. It is because the \ character is used as an escape character in Java. Hence the first backslash is used as an escape character for the second one.
0 Comments