Wednesday, December 21, 2011

Get All the Files and Folders Present inside the Directory

This is one of the way to get the list of all the files and folders present inside a particular folder,
I assume here that you have C:\store  folder in your computer with some subfolders and files inside it.


import java.io.File;
import java.io.IOException;

public class GetAllFilesAndFoldersInDirectory
{
public static void main(String[] args) throws IOException
{
File dir = new File("c:/store");
//All the files and folder names inside C:/store will be stored in this array
String[] list = dir.list();

if (list == null)
{
    // Either dir does not exist or is not a directory
}
else
{
    for (int i=0; i<list.length; i++)
    {
        // Get filename of file or directory
        String filename = list[i];
        System.out.print(filename+"::");
       
        //check if its a file or directory
        File tf = new File(dir.getPath(), list[i]);
        if (tf.isDirectory())
          System.out.println("directory");
          else System.out.println("file");
   
     }//for
}//else
}//main
}//class

No comments:

Post a Comment