如何检查Java中是否存在带通配符的文件? [英] How to check a file if exists with wildcard in Java?

查看:106
本文介绍了如何检查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

这篇关于如何检查Java中是否存在带通配符的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆