我有很多需要按文件名过滤的网址文件。我有一个单词的arraylist,应用程序需要在这些文件名中查找。我尝试过使用contains()函数,但它一直在询问CharSequence。我已经尝试将数组列表转换为CharSequence列表,但仍然无效。
以下是代码:
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
public class Filter {
public static File folder = new File("C:/Users/blah/blah);
static String temp = "";
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Reading files under the folder "+ folder.getAbsolutePath());
listFilesForFolder(folder);
}
public static void listFilesForFolder(final File folder){
ArrayList<String> aa = new ArrayList<String>
(Arrays.asList("one","two","three","four","five","six","seven"));
CharSequence[] cs = aa.toArray(new CharSequence[aa.size()]);
for(final File fileEntry : folder.listFiles()){
if(fileEntry.isDirectory()){
listFilesForFolder(fileEntry);
} else {
if (fileEntry.isFile()){
temp = fileEntry.getName();
if((temp.substring(temp.lastIndexOf('.') + 1,
temp.length()).toLowerCase()).equals("url"))
System.out.println("File = " + folder.getAbsolutePath()+ "\\" + fileEntry.getName());
}
}
}
}
}
答案 0 :(得分:2)
首选使用FileFilter
FileFilter urlFilter = new FileFilter() {
@Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true; // return directories for recursion
}
return file.getName().endsWith(".url"); // return .url files
}
};
使用Set
存储文件名而不是List
。 Set
会为您提供更好的查找效果。
Set<String> urlNames = new HashSet<String>(
Arrays.asList("one","two","three","four","five","six","seven"));
for (final File fileEntry : folder.listFiles(urlFilter)) { // listFiles using filter
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry); // recurse if directory
} else {
String fileName = fileEntry.getName();
// match file names w/o extension
if (urlNames.contains(fileName.substring(0, fileName.length() - 4))) {
System.out.println("File = " + fileEntry.getAbsolutePath());
}
}
}