Listing content of given Directory
Our goal is to read the content of given directory and list all the files and folders available inside it. To retrieve list of files/folders inside the given folder, we can call list() method of File class as shown in the example.
import java.io.*;
import java.util.*;
class ListDirContent
{
public static void main(String args[])
{
String dirname = "";
System.out.print("Enter a path:");
Scanner sc = new Scanner(System.in);
dirname = sc.nextLine();
File f1 = new File(dirname);
if (f1.isDirectory())
{
System.out.println("Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++)
{
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory())
{
System.out.println(s[i] + " is a directory");
}
else
{
System.out.println(s[i] + " is a file");
}
}
}
else
{
System.out.println(dirname + " is not a directory");
}
}
}





Recent Comments