File listRoots() method in Java with examples

The listRoots() method is a part of File class. The listRoots() function returns the root directories of all the available file System roots. It is guaranteed that the pathname of any file on the system will begin with any one of these roots.

Function Signature:

public static File[] listRoots()



Parameters: The function do not requires any parameters.

Return Value: The function returns File array, which contains all the file system roots .

Exception: This method do not throw any exceptions

Below programs will illustrate the use of listRoots() function:

Example 1: Try display all the root directories of the system





// Java program to demonstrate
// the use of File.listRoots() method
public class GFG {
    public static void main(String args[])
        // roots of the path name
        File root[] = File.listRoots();
        // check if the root is null or not
        if (root != null) {
            System.out.print("Roots are: ");
            // display the roots of the path name
            for (int i = 0; i < root.length; i++) {
                System.out.print(root[i].getPath() + " ");
            System.out.println("There are no roots");



Roots are: C:\ D:\ E:\ F:\ G:\ 

The programs might not run in an online IDE. please use an offline IDE and set the path of the file

My Personal Notes arrow_drop_up

Second year Department of Information Technology Jadavpur University

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.