Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java getting file extension without substring

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

like image 829
Yoda Avatar asked Jul 22 '12 20:07

Yoda


People also ask

How do I get the file extension of a file in Java?

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.

How do I get the filename extension?

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 '. '.

What does FilenameUtils normalize do?

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.


2 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.

like image 122
pb2q Avatar answered Sep 20 '22 00:09

pb2q


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?

like image 30
Jon Newmuis Avatar answered Sep 20 '22 00:09

Jon Newmuis