Java Reference
In-Depth Information
Listing 7-3. Listing All Available Root Directories on a Machine
// RootList.java
package com.jdojo.io;
import java.io.File;;
public class RootList {
public static void main(String[] args) {
File[] roots = File.listRoots();
System.out.println("List of root directories:");
for(File f : roots){
System.out.println(f.getPath());
}
}
}
List of root directories:
C:\
D:\
You can list all files and directories in a directory by using the list() or listFiles() methods of the File class.
The only difference between them is that the list() method returns an array of String , whereas the listFiles()
method returns an array of File . You can also use a file filter with these methods to exclude some files and directories
from the returned results.
Listing 7-4 illustrates how to list the files and directories in a directory. Note that the list() and listFiles()
methods do not list the files and directories recursively. You need to write the logic to list files recursively. You need to
change the value of the dirPath variable in the main() method. You may get a different output. The output shown is
the output when the program was run on Windows.
Listing 7-4. Listing All Files and Directories in a Directory
// FileLists.java
package com.jdojo.io;
import java.io.File;
public class FileLists {
public static void main(String[] args) {
// Change the dirPath value to list files from your directory
String dirPath = "C:\\";
File dir = new File(dirPath);
File[] list = dir.listFiles();
for(File f : list){
if (f.isFile()) {
System.out.println(f.getPath() + " (File)");
}
else if(f.isDirectory()){
System.out.println(f.getPath() + " (Directory)");
}
 
Search WWH ::




Custom Search