How do I get file extension in Java without using that silly lastIndexOf('.') etc.?
4 Answers
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.
3 Comments
getExtension), but read what it does: "returns the textual part of the filename after the last dot." That's exactly what he's already doing; there's no point in adding an entire library/dependency just for the same functionality (unless he's already using Apache Commons).getExtension is a bit more thorough that simply wrapping a lastIndexOf, for reasons that your own answer addresses, and e.g. dir.ext/file.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?
lastindexofisn't what you want or isn't working for you - sure I know this is approach has issues as well, but a little understanding as to why you are looking for another approach might help.