This article will talk about how to get filename without extension in Java language.
The file utility method helps you to get rid of the file extension from the file name. Here is an example.
Program:
class substring { public static void main(String[] args) { String fileName = "myfile.java"; if(!fileName.contains(".")) System.out.println("File Name = " + fileName); else { fileName = fileName.substring(0,fileName.lastIndexOf(".")); System.out.println("File Name = " + fileName); } } }
Output:
substring
Explanation:
We take a file named ‘myfile’ with the extension ‘.java’. Next, we check whether the filename contains ‘.’ or not. If it contains ‘.’, then go to the else part and get filename without an extension using substring() function. This function returns a substring from the given string by specifying the starting and ending index in parenthesis. The ending index is found when we encounter a ‘.’ character. We use the ‘lastIndexOf()’ function and pass the character as an argument until which we want the length of the string. And, then we get a substring from the string from 0 to the last index.
But, there is a condition that if we have two extensions in the filename, it removes the last extension from it. And, if there is no extension in the filename then it returns the same filename.
Program:
class substring { public static void main(String[] args) { String fileName = "substring.tar.gz"; if(!fileName.contains(".")) System.out.println("File Name = " + fileName); else { fileName = fileName.substring(0,fileName.lastIndexOf(".")); System.out.println("File Name = " + fileName); } } }
Output:
substring.tar
In this case, you can repeat steps twice to remove the second extension.
There is another condition that if a filename starts with ‘.’, then it removes the last extension from the filename.
Program:
class substring { public static void main(String[] args) { String fileName = ".substring.tar"; if(!fileName.contains(".")) System.out.println("File Name = " + fileName); else { fileName = fileName.substring(0,fileName.lastIndexOf(".")); System.out.println("File Name = " + fileName); } } }
Output:
.substring
Using a regular expression, we can also get a filename without an extension.
Here, I am defining some regular expressions:
- “[.^][^.]+$” – Remove last extension from the filename.
- “[.][^.]+$” – Remove last extension from the filename.
Program:
class substring { public static void main(String[] args) { String fileName = "substring.java"; fileName = fileName.replaceFirst("[.^][^.]+$", ""); System.out.println("File Name = " + fileName); } }
Output:
substring
If there is a filename that starts with ‘.’ and has no extension, it returns nothing.
If there is no filename and has only one extension then it returns nothing.
So, that’s all about how to get a filename without an extension.