如何检查Java中是否存在带通配符的文件?

问题描述:

我有一个目录,里面的文件名为a_id_XXX.zip

I have a directory, and inside it are files are named "a_id_XXX.zip".

如何给出 id 文件目录?检查文件是否存在?

How do check if a file exists given an id and File dir?

传递 FileFilter (此处匿名编码)进入 listFiles() 方法的方法 文件 ,如下所示:

Pass a FileFilter (coded here anonymously) into the listFiles() method of the dir File, like this:

File dir = new File("some/path/to/dir");
final String id = "XXX"; // needs to be final so the anonymous class can use it
File[] matchingFiles = dir.listFiles(new FileFilter() {
    public boolean accept(File pathname) {
        return pathname.getName().equals("a_id_" + id + ".zip");
    }
});



捆绑为方法,它看起来像:


Bundled as a method, it would look like:

public static File[] findFilesForId(File dir, final String id) {
    return dir.listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            return pathname.getName().equals("a_id_" + id + ".zip");
        }
    });
}

你可以打电话给:

File[] matchingFiles = findFilesForId(new File("some/path/to/dir"), "XXX");

或只是检查是否存在,

boolean exists = findFilesForId(new File("some/path/to/dir"), "XXX").length > 0