Java File Extension
The File extension is the suffix attached to a computer file. It can be identified easily as it directly appears in the file name after a period (.)
For example, consider a file name Demo.java, here the file name is Demo and .java is the file extension that represents the type of the file.
In this section, we will learn how to get extension of file through a Java program.
Java File Class
- The Java File class is defined in the io package. Another new Java package available for performing input/output operations is the java.nio package. It is introduced in JDK4.
- It is used to perform various file operations in the Java program.
- The File class has different methods and constructors that work with the file path name, renaming a file, deleting a file, creating a new file, etc.
- To use these methods and constructors, an instance of the File class needs to be created.
- File class instances are immutable, therefore once an instance is created with a specific pathname it cannot be changed.
Getting File Extension
There are two ways to get file extension in Java:
The following program uses the File class to identify the extension of the specified file that we give as input.
In the above Java program,
- An instance f of the File class from the io package is created. It creates an instance of the path passed to the constructor.
- On the next line an if statement is used to check whether the file exists or not. If it's true it will create the variables for storing the file type, file name and file extension.
- lastIndexOf() method returns the last occurrence of the character passed as an argument.
- substring() method is used to get the extension of the file after period (.)
- probeContentType() method from the nio package returns a string of content type. It may throw an IOException, therefore it is specified inside a try-catch block.
- And lastly, the file extension and content type are displayed on the console using a print()
Using Apache Commons IO
Apache Commons IO is the component of Apache derived from Java API. They provide multiple methods to perform different operations on files without creating an object of the file. In the following program we have used the FilenameUtils.getExtension() method to get the file extension.
In the above Java program, getExtension() method of the FilenameUtils class is used to get the file extension without creating the file object.