Java IO

Get extension of file in Java

This example shows various ways to extract file extension from the file name in Java.

How to get file extension in Java?

In most cases, file name consists of two parts file name and an extension. There are several ways in which extension can be extracted from the file name or file path.

1) Using Apache Commons IO library

Easiest way to get the extension of file is to use FileNameUtils class of Apache Commons IO library. FileNameUtils class has getExtension(String filename) static method which returns the extension of the file.

This method returns the extension of the file (usually the text after dot) or empty string if there is none.

Output

getExtension() method also works with Unix style directory name where the directory can also have dot (.) like below.

2) Using lastIndexOf() and substring() methods of String class

Output

Basically we start with extension as “” (empty string). Then we take the last position of the “.” (dot) and last position of “/”. If the last dot comes after the last “/”, we take substring after the last “.” which gives us the extension of the file. If there is no “.” after last “/”, file extension remains empty ( for example in case of “/etc/init.d/oracleasm” or “/usr/local/file”).

Note: if you are working with windows, change this line

to

For portable code across different operating systems, change it to

Please let us know your views in the comments section below.

Join 1000+ fellow learners! Enter your email address below: