java Java获取没有子字符串的文件扩展名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11603658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:44:59  来源:igfitidea点击:

Java getting file extension without substring

javafile-extension

提问by Yoda

How do I get file extension in Java without using that silly lastIndexOf('.')etc.?

如何在不使用愚蠢lastIndexOf('.')等的情况下在 Java 中获取文件扩展名?

回答by pb2q

The apache Commons library has FilenameUtils.getExtension().

apache Commons 库有FilenameUtils.getExtension().

You can look over the source starting here, and FilenameUtils.

您可以查看从这里开始的源代码和FilenameUtils

At least look over their implementation. It's pretty simple, they handle dir.ext/filecorrectly, and to handle something like file.tar.gzyou'll need a special case if you want to extract .tar.gzrather than just .gz.

至少看看他们的实现。这很简单,他们正确处理dir.ext/file,并且要处理file.tar.gz 之类的内容,如果您想提取.tar.gz而不仅仅是.gz ,则需要一个特殊情况。

回答by Jon Newmuis

That's probably the easiest way (also note that depending on the context, it's not necessarily correct, e.g. ".tar.gz").

这可能是最简单的方法(还要注意,根据上下文,它不一定正确,例如“.tar.gz”)。

You could also splitthe string based on the .character and take the last piece, but that seems just as difficult.

您也可以split根据.字符获取字符串并取最后一段,但这似乎同样困难。

Is there a particular reason whyyou're trying to avoid substringand lastIndexOf?

是否有特别的原因,为什么你想避免substringlastIndexOf

回答by Paul Vargas

Do not want to include external libraries? Use regular expressions:

不想包含外部库?使用正则表达式:

String extension = filename.replaceAll("^.*\.([^.]+)$", "");

回答by Entea

With guava

番石榴

Files.getFileExtension("some.txt")

Files.getFileExtension("some.txt")