How to get a filename without the extension in Java
Codemia Knowledge Hub ·
Take the last path segment with Path.getFileName(), then cut it at the last dot with lastIndexOf('.') and substring. If Apache Commons IO is already a dependency, FilenameUtils.getBaseName does both steps in one call. Decide up front how to handle names with several dots, no dot, or a leading dot.
Isolate the file name first
When you start from a full path, extract the last segment before removing the extension. In modern Java, use Path:
Working only on the file name stops a dot in a directory name from being mistaken for the extension separator.
Remove the last extension with lastIndexOf
In plain Java, find the last dot and keep what comes before it:
This prints:
Only the final extension is removed. That is usually the intent, since "archive.tar.gz" is commonly treated as a file named "archive.tar" with a "gz" extension.
Combine Path with a helper
Keeping path handling and string handling separate makes the code easier to test.
Apache Commons IO FilenameUtils.getBaseName
This is convenient when Commons IO is already in the codebase. It is usually not worth adding the library just for this.
Hidden files and multiple dots
Not every dot marks an extension. Unix-style hidden files such as .gitignore or .env start with a dot without having a base name plus extension in the usual sense, which is why the helper returns the whole string when the dot is at position 0. Code that cuts at the first dot instead turns these names into empty strings.
Also decide what "archive.tar.gz" should become. Some systems remove only "gz", others treat "tar.gz" as a compound extension. Removing only the final suffix with lastIndexOf is the safest default unless your domain needs special rules, and files with several dots or none at all should get explicitly defined behavior rather than guesswork.
Related reading
- How to get the first non-null value in Java?
- How to get the insert ID in JDBC?
- How to get the last value of an ArrayList
- How to get the name of a class without the package?
- How to get the number of threads in a Java process
- how to get the one entry from hashmap without iterating
- How to get the path of a running JAR file?
- How to get the path of src/test/resources directory in JUnit?
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.