Skip to content

Get extension of file in Java

This example shows how to get file extension from the file name in Java using lastIndexOf and substring methods as well as using the apache commons library.

How to get a file extension in Java?

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

1) Using the Apache Commons IO library

The easiest way to get the extension of a file is to use the FileNameUtils class of the Apache Commons IO library. The FileNameUtils class has the getExtension static method that returns the extension from the file name string.

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

Output

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

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

Output

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

Note: if you are working with a Windows operating system, change this line

to

For a portable code across different operating systems, change it to

This example is a part of the Java File class tutorial with examples.

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

About the author

Leave a Reply

Your email address will not be published.