Home Tutorial Java Core Files Java filename without extension

 
 

Java filename without extension
Posted on: June 10, 2006 at 12:00 AM
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

Related Tags for Java filename without 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.