Java file extension


 

Java file extension

In this section you will learn how to display the file extension of the file.

In this section you will learn how to display the file extension of the file.

Java file extension

In this section you will learn how to display the file extension of the file.

Description of code:

Files are usually known through their extensions. An extension differentiates the file from another file. It recognizes the file type. To find the extension from its file is a common task.

You can see in the give example, we have created an object of class File and specify a text file as an argument. The method getName() returns the name of the file. Then we have used substring() method to return a new string consists of file extension.

Here is the code:

import java.io.*;

public class FileExtension {
	public static void main(String[] args) {
		File file = new File("C:/file.txt");
		String fname = file.getName();
		String ext = fname
				.substring(fname.lastIndexOf('.') + 1, fname.length());
		System.out.println("Extension of file " + fname + " is: " + ext);
	}
}

Through the above code, you can determine the extension of any file.

Output:

Extension of file file.txt is: txt

Ads