如何检查Java 7 Path的扩展名 [英] How to check the extension of a Java 7 Path

查看:108
本文介绍了如何检查Java 7 Path的扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查看路径 (在Java 7中引入)以某种扩展结束。我尝试了 endsWith()方法,如下所示:

I'd like to check if a Path (introduced in Java 7) ends with a certain extension. I tried the endsWith() method like so:

Path path = Paths.get("foo/bar.java")
if (path.endsWith(".java")){
    //Do stuff
}

然而,这似乎不起作用,因为 path.endsWith(。java)返回false。似乎 endsWith()方法只有在最终目录分隔符之后的所有内容完全匹配时才返回true(例如 bar.java ),这对我来说不实用。

However, this doesn't seem to work because path.endsWith(".java") returns false. It seems the endsWith() method only returns true if there is a complete match for everything after the final directory separator (e.g. bar.java), which isn't practical for me.

那么如何检查路径的文件扩展名?

So how can I check the file extension of a Path?

推荐答案

Java NIO的 PathMatcher 提供 FileSystem.getPathMatcher(String syntaxAndPattern)

Java NIO's PathMatcher provides FileSystem.getPathMatcher(String syntaxAndPattern):

PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.java");

Path filename = ...;
if (matcher.matches(filename)) {
    System.out.println(filename);
}

参见查找文件教程了解详情。

这篇关于如何检查Java 7 Path的扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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