How do I get file extension in Java without using that silly lastIndexOf('.')
etc.?
String fileName = "Test. java"; String extension = Files. getFileExtension(fileName); And, also the Apache Commons IO provides the FilenameUtils class provides the getExtension method to get the extension of the file.
If filename is empty or null, getExtension(String filename) will return the instance it was given. Otherwise, it returns extension of the filename. To do this it uses the method indexOfExtension(String) which, in turn, uses lastIndexof(char) to find the last occurrence of the '. '.
Normalizes a path, removing double and single dot path steps, and removing any final directory separator. This method normalizes a path to a standard format. The input may contain separators in either Unix or Windows format. The output will contain separators in the format of the system.
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.
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
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With