Sunday, March 8, 2009

Java example to list all the items from the Folder/Location

As i always believe, Java is very powerfull language, providing us many different ways to use a specific task, here is one of the ways to list all the files or folders within the Folder location through the java program.
FolderFileList.java
--------------------
/* File : FolderFileList.java Purpose: Dumps all the Files and Folders from the location provided
Author : Anaparthi Subrahmanyam
Published: 2009-03-08
Usage Notification: Author doesnt own responsibility of any loss of data, responsibility for misuse or loss of any nature if this code is used. If possible, please provide link to this webpage
*/
import java.io.File;
public class FolderFileList
{
public static void main(String[] args)
{
String name = args[0];
File f = new File(name);
String fState = null;
try
{
if(!f.exists())
{
throw new Exception("Invalid location!!!");
}
if(f.isDirectory())
{
File[] listF = f.listFiles();
for (int i=0 ;i <>
{
fState = listF[i].isDirectory() ? "Folder":"File";
System.out.println(listF[i].getName()+"\t\t\t"+" === > "+fState);
}
}
else
{
System.out.println("Location provided is not a file directory.");
}
} catch (Exception e) { e.printStackTrace(); }
}
}
---------------------------

Provide the location as a command line argument as mentioned below(dont forget to compile):
prompt> java FolderFileList c:\folder_name