我正在尝试在多个目录中搜索文本文件,然后将目录路径添加到数组列表中。
我该怎么做?
这是我到目前为止所做的:
File folder = new File("path\\dir");
File folder1 = new File("path\\dir1");
ArrayList<File> flielist = new ArrayList<File>();
flielist.add(folder);
flielist.add(folder1);
for (int i = 0; i < flielist.size(); i++){
File dir = flielist.get(i);
System.out.println(dir.getName());
if(dir.listFiles() != null){
for (File file : dir.listFiles())
{
String filename = file.getName();
if(filename.equals("rashed")){
System.out.println("found" + file.getPath());
}
}
}
}
答案 0 :(得分:0)
public class FileSearch {
private List<String> result;
public List<String> getResult() {
if (result == null) {
result = new ArrayList<String>();
}
return result;
}
public static void main(String[] args) {
FileSearch fileSearch = new FileSearch();
fileSearch.search(new File("C:/Users"), "rashed.txt");
int count = fileSearch.getResult().size();
if (count == 0) {
System.out.println("\nNo result found!");
} else {
System.out.println("\nFound " + count + " result!\n");
for (String matched : fileSearch.getResult()) {
System.out.println("Found : " + matched);
}
}
}
public void search(File file, String filename) {
if (file.isDirectory()) {
System.out.println("Searching directory ... " + file.getAbsoluteFile());
//do you have permission to read this directory?
if (file.canRead()) {
if (file.listFiles() != null) {
for (File temp : file.listFiles()) {
if (temp.isDirectory()) {
search(temp, filename);
} else {
if (filename.equalsIgnoreCase(temp.getName())) {
getResult().add(temp.getAbsoluteFile().toString());
}
}
}
}
} else {
System.out.println(file.getAbsoluteFile() + "Permission Denied");
}
}
}
}