In this tutorial, we are going to present several ways to get the extension of a File using plain Java and libraries such as Guava or Apache Commons IO.
To test different approaches and solutions we create an empty text file under the path:
2. Get file extension using filter method from
Let's start with the first approach in plain Java:
This solution first checks if a filename contains the dot
. character. Then returns all characters after the last occurrence of the dot
This method will return an empty string if no extension found.
3. Obtain file extension with
Apache Commons IO library
Apache Commons IO library provides a special utility method to find filename extension. Let's check the following solution:
In this example, we used
FilenameUtils.getExtension(...) method that is the first step checks if given String is empty. Then with
lastIndexOf(...) function it finds the last occurrence of the dot character and returns all characters after that dot.
When filename does not contain any extension,
FilenameUtils.getExtension(...) will return an empty String.
Guava to get file extension
The last approach use
Files utility class from
This solution is very similar to
Apache Commons IO.
Files.getFileExtension(...) method will do all necessary work for us and return the file extension or an empty string if the file does not have an extension.
In this short article, we presented various ways to obtain file extension in Java. All approaches based on filename and we can simply implement one using