【问题标题】:Match path string using glob in Java在 Java 中使用 glob 匹配路径字符串
【发布时间】:2014-07-10 13:20:54
【问题描述】:

我有以下字符串作为全局规则:

**/*.txt

以及测试数据:

/foo/bar.txt
/foo/buz.jpg
/foo/oof/text.txt

是否可以使用 glob 规则(不将 glob 转换为正则表达式)来匹配测试数据并返回值条目?

一个要求:Java 1.6

【问题讨论】:

  • 在纯 Java 中,还是您愿意查看第三方实现?
  • 我更喜欢纯 Java。但是也可以接受 3rd 方库。
  • 你可以破解FileSystem.getPathMatcher来满足你的需要。
  • @BoristheSpider 谢谢。但是它从 Java 1.7 开始可用 - 我没有提到它 - 我必须用 Java 1.6 编译它
  • 它在 1.6 中不可用(请参阅stackoverflow.com/questions/1247772/…)。为什么你禁止自己使用“glob-to-regex”技术?您还可以使用wildcard

标签: java glob


【解决方案1】:

如果你有 Java 7 可以使用FileSystem.getPathMatcher:

final PathMatcher matcher = FileSystem.getPathMatcher("glob:**/*.txt");

这需要将您的字符串转换为Path 的实例:

final Path myPath = Paths.get("/foo/bar.txt");

对于早期版本的 Java,您可能会从 Apache Commons 的WildcardFileFilter 中获得一些帮助。您也可以尝试从 Spring 的 AntPathMatcher 中窃取一些代码 - 不过这非常接近 glob-to-regex 方法。

【讨论】:

  • 遗憾的是我必须用 1.6 编译 jar
【解决方案2】:

添加到上一个答案:org.apache.commons.io.FilenameUtils.wildcardMatch(filename, wildcardMatcher) 来自 Apache commons-lang 库。

【讨论】:

    【解决方案3】:

    FileSystem#getPathMatcher(String) 是抽象方法,不能直接使用。您需要首先获取 FileSystem 实例,例如默认:

    PathMatcher m = FileSystems.getDefault().getPathMatcher("glob:**/*.txt");
    

    一些例子:

    // file path
    PathMatcher m = FileSystems.getDefault().getPathMatcher("glob:**/*.txt");
    m.matches(Paths.get("/foo/bar.txt"));                // true
    m.matches(Paths.get("/foo/bar.txt").getFileName());  // false
    
    // file name only
    PathMatcher n = FileSystems.getDefault().getPathMatcher("glob:*.txt");
    n.matches(Paths.get("/foo/bar.txt"));                // false
    n.matches(Paths.get("/foo/bar.txt").getFileName());  // true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-31
      • 2017-01-09
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 2014-08-08
      • 2021-11-11
      相关资源
      最近更新 更多