I have many url files which need to be filtered by their file name. I have a an arraylist of words which the application needs to look for within those file names. I have tried using contains() function but it keeps asking for CharSequence. I have tried converting array list to CharSequence list but that still did not work.
Here is the code:
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());
}
}
}
}
}
Prefer using a 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
}
};
Use a Set
for storing file names instead of a List
. Set
would give you much better lookup performance.
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());
}
}
}
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.