Wednesday, July 8, 2009

How to get recursively listing all files in directory using Java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class AllFilesInFolder {
public static void main(String[] args) throws FileNotFoundException {
String folderName = "C:\\temp";
List<String> fileNames = getAllFiles(folderName);
System.out.println("All Files :: " + fileNames);
}

public static List<String> getAllFiles(String folderName) throws FileNotFoundException {
File aStartingDir = new File(folderName);
List<File> result = getFileListingNoSort(aStartingDir);
List<String> fileNames = new ArrayList<String>();
for (File f : result) {
String s = f.getAbsolutePath();
fileNames.add(s);
}

Collections.sort(result);
Collections.sort(fileNames);
return fileNames;
}

public static List<File> getFileListingNoSort(File aStartingDir) throws FileNotFoundException {
List<File> result = new ArrayList<File>();
File[] filesAndDirs = aStartingDir.listFiles();
List<File> filesDirs = Arrays.asList(filesAndDirs);
for (File file : filesDirs) {
if (!file.isDirectory()) result.add(file);
if (!file.isFile()) {
List<File> deeperList = getFileListingNoSort(file);
result.addAll(deeperList);
}
}
return result;
}
}

1 comment:

  1. Hi Binod,
    Please provide me some help in creating a utility/tool which will convert a XML file to XSD.

    ReplyDelete

You can put your comments here (Either feedback or your Question related to blog)