【问题标题】:Read file that changes name frequently in Java读取Java中频繁更改名称的文件
【发布时间】:2019-12-17 08:54:59
【问题描述】:

我需要读取一个具有动态名称的 xml 文件。文件名类似于“1234_employees.xml”,其中的数字每天都在变化。文件夹中只有一个.xml。

regex 不适用于文件/路径吗?

类似:

File myxml = new File("*employees.xml");

【问题讨论】:

  • 顺便说一句,这不是正则表达式,而是glob。知道要搜索的正确术语会使一切变得更容易。
  • 你是对的,谢谢!

标签: java file path glob


【解决方案1】:

你可以使用WildcardFileFilter:

File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("*employees.xml");

File employeesXml = dir.listFiles(fileFilter)[0];

你需要安装这个库:

https://mvnrepository.com/artifact/org.apache.commons/commons-io/1.3.2

【讨论】:

    【解决方案2】:

    您可以使用FilenameFilter,如下所示

    for (File inputFile : yourDirectory.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith("employees.xml");
            }
    })) { 
         // process inputFile here
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-11
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-28
      相关资源
      最近更新 更多