问题
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