How to get file extension in Java


This tutorial will help you to get the file extension name through the Java programme. Usually file extension name is a string of characters attached to a filename, usually preceded by a full stop and indicating the format of the file.

For example: Sample.txt, FactorialExample.java, Certificate.pdf, etc.

We can get it from a simple core Java programme or by using third party API.

Using Core Java Programme

In this example, we have simply used the String class method lastIndexOf().

FileExtension.java
package org.websparrow;

public class FileExtension {

	public static void main(String[] args) {

		String fileName = "Hello.java";
		String extension = "";
		String extensionNew = "";
		int index = fileName.lastIndexOf(".");

		if (index > 0) {

			extension = fileName.substring(index + 1); // return ---> "java"
			extensionNew = fileName.substring(index); // return ---> ".java"
		}

		System.out.println("File extension is: " + extension);
		System.out.println("File extension new  is: " + extensionNew);
	}
}

Using Apache Commons IO

Apache Common IO is very popular API for file manipulations. To get the file extension we simply call the getExtension() method of class FilenameUtils.

FileExtensionNew.java
package org.websparrow;

import org.apache.commons.io.FilenameUtils;

public class FileExtensionNew {
	
	public static void main(String[] args) {

		String extension = "";
		String extension2 = "";
		
		try {
			
			extension = FilenameUtils.getExtension("Hello.java");              // return ---> "java"
			extension2 = FilenameUtils.getExtension("home/java/Test.jar");    // return ---> "jar"
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("File extension is: " + extension);
		System.out.println("File extension  is: " + extension2);
	}
}

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.