本文介绍了如何检查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的提供:

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的扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 17:11