Your Computer Science Resource

HOW-TO: Retrieve a File’s extension in Java

For some strange reason, there’s no getFileExtension() or getExtension() method in Java’s File class (perhaps because Files do not necessarily always have extensions in every platform?). Nevertheless, that doesn’t mean we can’t do it on our own. All it takes is one line of code!

Suppose you have a File named file. We know that an extension usually follows a period. For example, in the file temp.txt, the txt part is the extension, indicating what the file type is.

Now we just have to figure out how to isolate this part of the filename. Using the subString() method of the String class, we can do just that.

The Code

// Assuming `file` is a File mentioned before this
String extension = file.getName().substring( file.getName().lastIndexOf('.') + 1, file.getName().length() );

Example

In case the above line of code didn’t clear things up, here is a full working example:

import java.io.File;

public class FileExtension {

	public static void main( String[] args ) {

		File file = new File("temp.txt");
		String extension = file.getName().substring( file.getName().lastIndexOf('.') + 1, file.getName().length() );
		System.out.println( "Filename: " + file.toString() );
		System.out.println( "Extension: " + extension );

	}

}

Tags: , ,

Leave a Reply