Thursday 24 May 2012

Recursively list files in Java

We can use java.io.File class for recursively listing all files under a directory in Java. A File class object is an abstract representation of file and directory pathnames.

new File("pathname");
 
Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname. 

The java.io.File class provides many methods for getting information about a file system. Please visit Load a file in Java to learn more about it.


We can use File class listFiles() method for listing all the files and directories under a given directory (Note: This method won't recursively list files).


File f=new File("pathname");
File[]list=f.listFiles();


The listFiles() method 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.

Pathnames denoting the directory itself and the directory's parent directory are not included in the result.

Each resulting abstract pathname is constructed from this abstract pathname using the File(File, String) constructor.Therefore if this pathname is absolute then each resulting pathname is absolute; if this pathname is relative then each resulting pathname will be relative to the same directory.

There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.


To recursively list all the files under a directory in Java use the following code


import java.io.File;

public class ListFiles {

  /**Pass pathname to be traversed as command line argument**/

    public static void main(String args[]) {

        File file = new File(args[0]);

        displayFiles(file);
    }

    public static void displayFiles(File f) {

        if (f.isFile()) {

            System.out.println("File:" + f.getPath());

        } else {

            System.out.println("Folder -->" + f.getPath());

            if (f.listFiles() != null) {

                for (File file : f.listFiles())

                    displayFiles(file);
            }
        }
    }

}


The above code recursively list all the files and folders under the given file path.

No comments:

Post a Comment