gpt4 book ai didi

java - Java中如何使用通配符检查文件是否存在?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:00:29 24 4
gpt4 key购买 nike

我有一个目录,其中的文件名为 "a_id_XXX.zip"

如何根据 idFile dir 检查文件是否存在?

最佳答案

传递 FileFilter (此处编码为 anonymously )进入 listFiles()目录的方法 File ,像这样:

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");
}
});


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

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 - Java中如何使用通配符检查文件是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8752034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com