Overview. In this tutorial, we'll show how to get the file extension in Java. We'll focus on major approaches to the problem. The characters after the final '.' will be returned. Therefore, if file is...
Overview. In this tutorial, we’ll show how to get the file extension in Java. We’ll focus on major approaches to the problem. The characters after the final ‘.’ will be returned. Therefore, if file is ‘jarvis.txt’ it will return ‘txt’.
Getting the File Extension. We’ll implement each approach and follow with special cases. This example hardcodes extensions to display predefined results. For ‘.tar.gz’, we display ‘tar.gz’, not ‘gz’. Another example shows parsing extensions.
The extension is the last part after ‘.’. To get it, first create a File object. Examples: ‘Test.txt’ extension is ‘txt’. ‘maven-3.8.6-settings.xml’ extension is ‘xml’. We can use lastIndexOf() and substring(). Extensions are identified by ‘.’.
The File class represents file pathnames. Its probeContentType() method gets the extension. To get extension, we can also use FilenameUtils getExtension(). It belongs to Apache library so download JARs.
While doing file I/O you may need the extension. Since no File API method exists, use String methods to get it. Another option is FilenameUtils but requires Apache IO jar. The program shows how to get extension in Java using lastIndexOf() and substring().
The file name has two parts: the name and extension. Extract extension using substring() or Apache Commons IO library.