Share on Google+Share on Google+

Java file extension

Advertisement
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

Advertisements

Advertisement

Posted on: July 27, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.