Java getting file extension without substring

强颜欢笑 提交于 2020-01-03 09:57:49

问题


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


回答1:


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.




回答2:


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?




回答3:


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

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



回答4:


With guava

Files.getFileExtension("some.txt")



来源:https://stackoverflow.com/questions/11603658/java-getting-file-extension-without-substring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!