How to get file extension in Java

In this post, we are going to learn to get an extension of a file using Java code. The extension of a file is a flag that indicates the type of file such as pdf, txt, doc, etc. There are several files extension in the computer field that is used to differentiate the file from another file.

The extension is part of the file name and placed at the end of the file name such as test.txt, officefile.doc, etc.

Here, we have some examples that show how to get an extension of any file in Java program. It is very helpful to know the file extension while reading and uploading a file to the server so that we get the required type of files only.

Time for an Example:

Let's create an example to get the file extension. Here, we have a text file file.txt of which we are getting an extension. We used lastIndexOf() and substring() methods of String class to identify the extension.

import java.io.IOException;
public class Main {
	public static void main(String[] args) throws IOException{  
		String extension = "null";
		String fileName = "file.txt";
		int i = fileName.lastIndexOf('.');
		if (i > 0) {
		    extension = fileName.substring(i+1);
		}
		System.out.println(extension);
	}
}


txt

Time for another Example:

If the file is encrypted or compressed then it may have more then one extension. In this case, we can use the following Java code where the file is compressed and has .tar.gz extensions.

import java.io.IOException;
public class Main {
	public static void main(String[] args) throws IOException{  
		String extension = null;
		String fileName = "file.tar.gz";

		int i = fileName.lastIndexOf('.');
		if (i > 0) {
		    extension = fileName.substring(i+1);
		}
		System.out.println(extension);
	}
}


gz