How to get the filename without the extension in Java?

Here is the consolidated list order by my preference.

Using apache commons

import org.apache.commons.io.FilenameUtils;

String fileNameWithoutExt = FilenameUtils.getBaseName(fileName);
                          
                           OR

String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);

Using Google Guava (If u already using it)

import com.google.common.io.Files;
String fileNameWithOutExt = Files.getNameWithoutExtension(fileName);

Files.getNameWithoutExtension

Or using Core Java

1)

String fileName = file.getName();
int pos = fileName.lastIndexOf(".");
if (pos > 0 && pos < (fileName.length() - 1)) { // If '.' is not the first or last character.
    fileName = fileName.substring(0, pos);
}
if (fileName.indexOf(".") > 0) {
   return fileName.substring(0, fileName.lastIndexOf("."));
} else {
   return fileName;
}
private static final Pattern ext = Pattern.compile("(?<=.)\\.[^.]+$");

public static String getFileNameWithoutExtension(File file) {
    return ext.matcher(file.getName()).replaceAll("");
}

Liferay API

import com.liferay.portal.kernel.util.FileUtil; 
String fileName = FileUtil.stripExtension(file.getName());

If you, like me, would rather use some library code where they probably have thought of all special cases, such as what happens if you pass in null or dots in the path but not in the filename, you can use the following:

import org.apache.commons.io.FilenameUtils;
String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt);

The easiest way is to use a regular expression.

fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");

The above expression will remove the last dot followed by one or more characters. Here's a basic unit test.

public void testRegex() {
    assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", ""));
    assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", ""));
}

Tags:

Java

File