In his section, you will learn how to get the file name without extension.
In his section, you will learn how to get the file name 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) { |
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 |