Java - File listRoots() Method with Example



Description

The Java File listFiles() returns an array of abstract pathnames indicating the files and directories in the directory indicated by this abstract pathname that satisfy the specified filter.

Declaration

Following is the declaration for java.io.File.listRoots() method −

public static File[] listRoots()

Parameters

NA

Return Value

The method returns an array of File Objects indicating the available file system roots. The method returns null, if the set of roots could not be determined.

Exception

NA

Example

The following example shows the usage of Java File listRoots() method. We've created an array of files as File[] paths. Then we're getting all the roots in the current file system using File.listRoots() method call. As next step, we've iterated the result and print each path. In case of any exception during invocation of this method, we've handled the exception and printed the stack trace to figure out the root cause.

package com.tutorialspoint;
import java.io.File;
public class FileDemo {
   public static void main(String[] args) {      
      File[] paths;      
      try {  
      
         // returns pathnames for files and directory
         paths = File.listRoots();
         
         // for each pathname in pathname array
         for(File path:paths) {
         
            // prints file and directory paths
            System.out.println(path);
         }
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

C:\
F:\
java_file_class.htm
Advertisements