0

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());

            }
           }
          }
         }

        }
4

1 回答 1

3

更喜欢使用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
    }
};

使用 aSet来存储文件名而不是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());
        }
    }
}
于 2013-08-22T16:23:39.947 回答