Share on Google+Share on Google+

Java filename without extension

Advertisement
In his section, you will learn how to get the file name without extension.

Java filename without extension

In his section, you will learn how to get the file name without extension.

Description of code:

In one of the previous sections, we have discussed the extraction of file extension from the given file. Here we going to do just reverse of that i.e retrieving file name from the given file without extension.

You can see in the given example, we have created an object of File class and specify a file string into the constructor of the class. The method getName() returns the name of the file which is then used with the lastIndexOf() method and returns the index of dot(.) from the file name. Then using  the following code, we have got the file name without extension.

if (index > 0 && index <= file.getName().length() - 2) {
System.
out.println("Filename without Extension: "
+ file.getName().substring(0, index));
}

Here is the code:

import java.io.File;

public class FileNameWithoutExtension {
	public static void main(String[] args) {
		File file = new File("C:/data.txt");
		int index = file.getName().lastIndexOf('.');
		if (index > 0 && index <= file.getName().length() - 2) {
			System.out.println("Filename without Extension: "
					+ file.getName().substring(0, index));
		}
	}
}
Filename without Extension: data

Advertisements

Advertisement

Posted on: June 10, 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.