Table of Contents
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package org.arpit.java2blog; public class RemoveExtensionFromFile { public static void main(String[] args) { String fileName = "C:\\txtFiles\\temp.txt"; String fileNameWithoutExtension = removeExtension(fileName); System.out.println("Complete file path without extension => "+fileNameWithoutExtension); } public static String removeExtension(final String s) { return s != null && s.lastIndexOf(".") > 0 ? s.substring(0, s.lastIndexOf(".")) : s; } } |
Output:
1 2 3 |
Complete file path without extension => C:\txtFiles\temp |
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(.)
1 2 3 4 5 6 7 8 9 10 11 |
package org.arpit.java2blog; public class RemoveExtensionFromFileReplaceAll { public static void main(String[] args) { String fileName = "C:\\txtFiles\\temp.txt"; String fileNameWithoutExtension = fileName.replaceAll("\\.\\w+",""); System.out.println("Complete file path without extension => "+fileNameWithoutExtension); } } |
Output:
1 2 3 |
Complete file path without extension => C:\txtFiles\temp |
Further reading:
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
.
1 2 3 4 5 6 7 |
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> |
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package org.arpit.java2blog; import org.apache.commons.io.FilenameUtils; public class RemoveExtensionFromFileNameApache { public static void main(String[] args) { String fileName = "C:\\txtFiles\\temp.txt"; String fileNameWithoutExtension = FilenameUtils.getBaseName(fileName); System.out.println("File name without extension => "+fileNameWithoutExtension); String fileNamePathWithoutExtension = FilenameUtils.removeExtension(fileName); System.out.println("Complete file path without extension => "+fileNamePathWithoutExtension); } } |
Output:
Complete file path without extension => C:\txtFiles\temp
That’s all about remove extension from filename in java.