【问题标题】:Find latest file that matches pattern in folder在文件夹中查找与模式匹配的最新文件
【发布时间】:2015-02-11 20:37:50
【问题描述】:

我正在编写一个需要 2 个输入的方法:

  1. String name

  2. String path

然后输出最新的pdf(以pdf为扩展名)文件名,以name(这是一个变量)开头并且在路径中。

我正在使用:

public String getLatestMatchedFilename(String path, String name){
    File dir=new File(path);    
    File[] files = dir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.startsWith();
        }
    });
}

但是,我不知道如何将 name 中的值传递给 accept 方法,因为它是一个变量并且每次都会更改。

【问题讨论】:

  • 成功了。现在我可以将值传递给接受方法。谢谢

标签: java filter filelist


【解决方案1】:

将名称更改为名为@9​​87654321@ 的变量之一。在您的方法中使用final 标记String name 参数(或任何名称),以便在匿名类中使用并直接使用它。

以下是代码的外观:

public String getLatestMatchedFilename(String path, final String name) {
    File dir = new File(path);    
    File[] files = dir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String nameFilter) {
            return nameFilter.startsWith(name);
        }
    });
    // rest of your code ...
}

【讨论】: