Home Tutorial Java Core Files Java file extension

 
 

Java file extension
Posted on: July 27, 2006 at 12:00 AM
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

Related Tags for Java file extension:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.