Listing Dtrectories inside a Folder

Introduction

In this lesson i am going to explain how to list and print directories inside a folder.We are using Java.io.File through out this code.

 Listing Directories inside a folder

Create a class Folder and we are aware folders are also treated as files only.That Folder class contains a file which is folder itself and folder name and a List of directories in it.

The following code

package bachifriends;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
class Folder 
{
File file;
boolean isaFile;
String FolderName;
List<Folder> list;

public Folder(File file, boolean isaFile, String folderName) {
super();
this.file = file;
this.isaFile = isaFile;
this.FolderName = folderName;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public boolean isIsaFile() {
return isaFile;
}
public void setIsaFile(boolean isaFile) {
this.isaFile = isaFile;
}
public String getFolderName() {
return FolderName;
}
public void setFolderName(String folderName) {
FolderName = folderName;
}
public List<Folder> getList() {
return list;
}
public void setList(List<Folder> list) {
this.list = list;
}
public void listFolders(Folder f)
{
List<Folder> list=new ArrayList();
File[] flist=f.getFile().listFiles();
for(int i=0;i<flist.length;i++)
{
if(flist[i].isDirectory())
{
Folder dir=new Folder(flist[i],f.isaFile,flist[i].getName());
list.add(dir);
}

}

this.list=list;

}
public void print()
{
Iterator<Folder> i=this.list.iterator();
while(i.hasNext())
{
System.out.println(i.next().FolderName);
}

}

public static void main(String[] args) {
try
{
File f=new File("D:\\books");

if(f.exists())
{
System.out.println("hjsdhjsd");
if(f.isDirectory())
{
Folder folder=new Folder(f, false,f.getName());
folder.listFolders(folder);
folder.print();
}
}

}
catch(Exception e)
{
System.out.println("error s "+e);
}
}
}

The above code lists all the directories inside the folder books.
If found any problem write a feed back.
Boiled peanuts were the ceremonious gift

1 comments:

  1. Good explanation, but how can i use this in my swing application.

    ReplyDelete