list all files in the folder and also sub folders [duplicate]
Possible Duplicate:
List all files from a directory recursively with Java
How can i return a file array that include all files on the folder and also sub folders my method just work for folder and it doesn't include sub folders .
public File[] listf(String directoryName) {
// .............list file
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
System.out.println(file.getAbsolutePath());
} else if (file.isDirectory()) {
listf(file.getAbsolutePath());
}
}
System.out.println(fList);
return fList;
}
Solution 1:
Using you current code, make this tweak:
public void listf(String directoryName, List<File> files) {
File directory = new File(directoryName);
// Get all files from a directory.
File[] fList = directory.listFiles();
if(fList != null)
for (File file : fList) {
if (file.isFile()) {
files.add(file);
} else if (file.isDirectory()) {
listf(file.getAbsolutePath(), files);
}
}
}
Solution 2:
Use FileUtils from Apache commons.
listFiles
public static Collection<File> listFiles(File directory,
String[] extensions,
boolean recursive)
Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.
Parameters:
directory - the directory to search in
extensions - an array of extensions, ex. {"java","xml"}. If this parameter is null, all files are returned.
recursive - if true all subdirectories are searched as well
Returns:
an collection of java.io.File with the matching files
Solution 3:
You can return a List
instead of an array and things gets much simpler.
public static List<File> listf(String directoryName) {
File directory = new File(directoryName);
List<File> resultList = new ArrayList<File>();
// get all the files from a directory
File[] fList = directory.listFiles();
resultList.addAll(Arrays.asList(fList));
for (File file : fList) {
if (file.isFile()) {
System.out.println(file.getAbsolutePath());
} else if (file.isDirectory()) {
resultList.addAll(listf(file.getAbsolutePath()));
}
}
//System.out.println(fList);
return resultList;
}