I know how to create list to contain all of files in directory by this code
String path = "c:/test";
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
but if i have directory has files and sub directory and the sub directory has files and sub-sub directory and so on..
how I create list contain all files in directory and sub directory ?
You could do like this:
protected java.util.List<File> setDirMap(File inputDir) {
if (!inputDir.isDirectory()) {
throw new IllegalArgumentException("Input File is not a directory");
}
Set<File> ans = new HashSet<File>();
ans.add(inputDir);
File[] dir = inputDir.listFiles(new FileFilter() {
@Override
/**
* Returns true if pathname is a directory. False if not
*/
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
return true;
} else {
return false;
}
}
});
ans.addAll(Arrays.asList(dir));
for (File current : dir) {
ans.addAll(setDirMap(current));
}
return new ArrayList<File>(ans);
}
This returns all directories and sub-directories. You can then check each directory for whatever you want
Try this code, this uses recursion....
import java.io.File;
import java.util.ArrayList;
public class FindIt {
private ArrayList<String> arList = new ArrayList<String>();
public void find(String s) {
File f = new File(s);
File[] fArr = f.listFiles();
for (File x : fArr) {
if (x.isFile()) {
if (x.getName().endsWith(".txt")) {
arList.add(x.getName());
}
else {
continue;
}
}
else {
find(x.getAbsolutePath());
}
}
}
public static void main(String[] args) {
FindIt f = new FindIt();
f.find("D:\\xtop");
for (String fileName : f.arList) {
System.out.println(fileName);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.