Java getting file extension without substring

2019-06-20 01:45发布

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

4条回答
三岁会撩人
2楼-- · 2019-06-20 02:25

With guava

Files.getFileExtension("some.txt")

查看更多
Fickle 薄情
3楼-- · 2019-06-20 02:40

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

String extension = filename.replaceAll("^.*\\.([^.]+)$", "$1");
查看更多
姐就是有狂的资本
4楼-- · 2019-06-20 02:42

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

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

Is there a particular reason why you're trying to avoid substring and lastIndexOf?

查看更多
小情绪 Triste *
5楼-- · 2019-06-20 02:49

The apache Commons library has FilenameUtils.getExtension().

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

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

查看更多
登录 后发表回答