how to get file extension in java

This example shows you how you can get the file extension in java.

You can get the file extension by getting the sub string of last ‘.’ character of file name.

Below is the example of getting file extension in java.

package com.java.connect.io;

import java.io.File;

//how to get file extension in java
public class FileExtensionExample {

	public static void main(String[] args) {
		// Get the file instance
		File file = new File("lord_ganesh.jpg");

		String extension = getExtension(file.getName());
		System.out.println("The file extension is : " + extension);
	}

	// Call this method to get the extension by passing the file name
	public static String getExtension(String fileName) {
		if (fileName == null) {
			return null;
		}

		int index = fileName.lastIndexOf(".");
		if (index == -1) {
			return "";
		}

		return fileName.substring(index + 1);
	}
}

The output of the above example will be as:

The file extension is : jpg