How to Get Filename Without Extension in Java

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:

Output:

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:

Output:

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:

Output:

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:

Output:

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.

Leave a Comment

Your email address will not be published. Required fields are marked *