我想实现对匹配关键字的文件或文件夹的搜索。我正在使用以下代码,但返回的文件夹与字符串不匹配。返回所有目录。请问有什么问题吗?
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
public class SearchFiles {
public static void main(String args[]){
File directory=new File("C:/Users");
String keyword="Logs";
IOFileFilter fileFilter = new IOFileFilter() {
public boolean accept(File directory, String fileName) {
return directory.isDirectory()&&fileName.contains(keyword);
}
@Override
public boolean accept(File arg0) {
if(arg0.getName().contains(keyword)){return true;}
else{
return false;
}
}
};
List<File> files = (List<File>)FileUtils.listFilesAndDirs(directory, fileFilter, TrueFileFilter.INSTANCE);
for (File file : files) {
try {
System.out.println("file: " + file.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} }