Skip to content

Instantly share code, notes, and snippets.

@Kozlov-V
Created August 2, 2013 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kozlov-V/6139905 to your computer and use it in GitHub Desktop.
Save Kozlov-V/6139905 to your computer and use it in GitHub Desktop.
FIle dir to list
void ================================================
File dir = new File ("data/user/VRP");
List<File> files = null;
try {
files = getFileListing(dir);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
======================================================
static public List<File> getFileListing(
File aStartingDir
) throws FileNotFoundException {
validateDirectory(aStartingDir);
List<File> result;
result = getFileListingNoSort(aStartingDir);
//Collections.sort(result);
return result;
}
// PRIVATE //
static private 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) {
result.add(file); //always add, even if directory
if ( ! file.isFile() ) {
//must be a directory
//recursive call!
List<File> deeperList = getFileListingNoSort(file);
result.addAll(deeperList);
}
}
return result;
}
static private void validateDirectory (
File aDirectory
) throws FileNotFoundException {
if (aDirectory == null) {
throw new IllegalArgumentException("Directory should not be null.");
}
if (!aDirectory.exists()) {
throw new FileNotFoundException("Directory does not exist: " + aDirectory);
}
if (!aDirectory.isDirectory()) {
throw new IllegalArgumentException("Is not a directory: " + aDirectory);
}
if (!aDirectory.canRead()) {
throw new IllegalArgumentException("Directory cannot be read: " + aDirectory);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment