The code below demonstrates how to list the file system root directories.
Code:private static void doListRoots() {
File[] roots = File.listRoots();
for (int i=0; i<roots.length; i++) {
System.out.println("Root[" + i + "] = " + roots[i]);
}
}
Printable View
The code below demonstrates how to list the file system root directories.
Code:private static void doListRoots() {
File[] roots = File.listRoots();
for (int i=0; i<roots.length; i++) {
System.out.println("Root[" + i + "] = " + roots[i]);
}
}
We can also use the following code to get all the subdirectories and files with any given folder.
public class DirectoryReader {
public static void populateArrayListsWithDirAndFilesInFolders(String currDirectory, ArrayList<String> directories, ArrayList<String> files )
{
File folder = new File(currDirectory);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if(listOfFiles[i].isFile())
{
files.add(listOfFiles[i].getPath());
}
if (listOfFiles[i].isDirectory())
{
directories.add(listOfFiles[i].getPath());
//System.out.println("Directory name-" + listOfFiles[i].getName() + " path-" + listOfFiles[i].getPath());
}
}//End of for
}//End of populateArrayListWithDirInFolders
public static void getAllSubdirectoriesAndFiles(String basedir)
{
ArrayList<String> directories = new ArrayList<String>();
ArrayList<String> files = new ArrayList<String>();
directories.add(basedir);
int currentLocationInArrayList = 1;
while(currentLocationInArrayList<=directories.size ())
{
String currDirectory = directories.get(currentLocationInArrayList-1);
currentLocationInArrayList++;
populateArrayListsWithDirAndFilesInFolders(currDir ectory, directories, files );
}//End of while
System.out.println("*****\nFollowing are the files under the directory-" + basedir + "\n*****\n");
for(String file : files)
System.out.println(file);
System.out.println("*****\nFollowing are the subdirectories under the directory-" + basedir + "\n*****\n");
for(String directory : directories)
System.out.println(directory);
}//End of getAllSubdiectories
public static void main(String args[])
{
getAllSubdirectoriesAndFiles("E://workspace//working//");
}//End of main
} //End of directoryReader