How to get file extension in Java?

August 31, 2017

Simple Java parser

If you want to get a file extension from the file path you can try this code:
The fileName is a variable which contains the name of your file. lastIndexOf() will give you the index of the last dot in a file name. The if statement guarantees that you will get a substring from dot to the end of a string (which usually is the file extension). Although, this solution is not perfect. It will work only with simple Windows-like file names. When it comes to the Unix ones like archive.tar.gz, it won’t work.

Apache Commons IO

If you are familiar with Apache Commons, you can use its FilenemUtils class. This contains the proper method named getExtension() which deal with the problems listed in the previous solution. Here’s how to use that:
 

Click here to add a comment

Leave a comment:


Privacy Preference Center

Necessary

Advertising

Analytics

Other