This post will discuss how to get the filename without extension in Java. The solution should return the file name before the last dot.

1. Using String.substring() method

The idea is to use the lastIndexOf() method to get the index of the last occurrence of the dot (.) in the given file name. Then you can extract the filename without extension using the substring() method, as shown below:

Download Code

 
The above code throws a java.lang.StringIndexOutOfBoundsException if the file name has no extension. You can handle this case by checking the return value of the lastIndexOf() method, which returns -1 if the dot does not occur. This is demonstrated below:

Download  Run Code

2. Using Apache Commons IO

Another option is to use the FilenameUtils class provided by Apache Commons IO library. It provides the removeExtension() method to removes the extension from a filename. If the fileName contains a path, it doesn’t remove it.

Download Code

 
Alternatively, you can also use the getBaseName() method from the FilenameUtils class that additionally removes the path from the filename (if present), along with the extension. It is similar to the basename Unix command.

Download Code

3. Using Guava

If your project uses the Guava library over Apache Commons, consider using the getNameWithoutExtension() method from the Files class. It returns the file name without its extension or path, similar to the basename Unix command.

Download Code

4. Using Regex

Another option is to use the regular expression \.\w+$ with the replaceAll() method that removes the last dot and all the characters that follow it.

Download  Run Code

That’s all about getting the filename without extension in Java.