Javatpoint Logo
Javatpoint Logo

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.

FileTypeDemo.java

Output:

Java File Extension

In the above Java program,

  1. An instance f of the File class from the io package is created. It creates an instance of the path passed to the constructor.
  2. 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.
  3. lastIndexOf() method returns the last occurrence of the character passed as an argument.
  4. substring() method is used to get the extension of the file after period (.)
  5. 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.
  6. 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.

GetFileExtensionApache,java

Output:

Extension: txt

In the above Java program, getExtension() method of the FilenameUtils class is used to get the file extension without creating the file object.


Next TopicJava Pi





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA