How to Remove Extension from Filename in Java

In this post, we will see how to remove extension from filename in java.

Ways to Remove extension from filename in java

There are multiple ways to remove extension from filename in java. Let’s go through them.

Using substring() and lastIndexOf() methods

You can first find last index of dot(.) using String’s lastIndexOf() method and then use substring() to extract the part of String upto the last index of dot(.).

Here is an example:

Output:

You can also get extension of file in java using above method.

Using replaceAll() method

You can also use String’s replaceAll() method to remove extension of filename in Java. We will use regex to identify characters after last dot(.) and replace it with empty string.
Here \\.\\w+

  • \\. is used to find . in the String
  • \\w+ is used to find any character after dot(.)

Output:

Using Apache common library

You can use FilenameUtils‘s getBaseName() method to get filename without extension. If you are looking for complete path, you can use removeExtension() method.
Add the following dependency to pom.xml.

Here is an example:

Output:

File name without extension => temp
Complete file path without extension => C:\txtFiles\temp

That’s all about remove extension from filename in java.

Was this post helpful?

Leave a Reply

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