Java
Filename
File Extension
Programming
Coding Tips

How to get the filename without the extension in Java?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Getting a filename without its extension sounds simple, but edge cases make the implementation matter. You need to decide whether you are stripping the extension from a plain name, from a full path, or from a file that may contain multiple dots or no extension at all.

Start by Isolating the Name Component

If you are given a full path, separate the last path segment before removing the extension. With modern Java, Path is a good place to start:

java
1import java.nio.file.Path;
2
3Path path = Path.of("/tmp/reports/summary.csv");
4String fileName = path.getFileName().toString();
5
6System.out.println(fileName); // summary.csv

Working on only the filename avoids mistakes where a dot in a directory name is treated like the file extension separator.

Remove the Last Extension with lastIndexOf

For standard cases, the simplest Java-only approach is to look for the last dot and take the part before it:

java
1public static String baseName(String fileName) {
2    int dot = fileName.lastIndexOf('.');
3    if (dot <= 0) {
4        return fileName;
5    }
6    return fileName.substring(0, dot);
7}
8
9public static void main(String[] args) {
10    System.out.println(baseName("report.pdf"));
11    System.out.println(baseName("archive.tar.gz"));
12    System.out.println(baseName("README"));
13}

This prints:

text
report
archive.tar
README

Using lastIndexOf means only the final extension is removed. That is usually what people want, because "archive.tar.gz" is commonly treated as a file named "archive.tar" with a "gz" extension.

Combine Path and a Helper Method

A practical pattern is to extract the file name from the path and then reuse a helper:

java
1import java.nio.file.Path;
2
3public class FileNames {
4    public static String baseName(Path path) {
5        String fileName = path.getFileName().toString();
6        int dot = fileName.lastIndexOf('.');
7        if (dot <= 0) {
8            return fileName;
9        }
10        return fileName.substring(0, dot);
11    }
12
13    public static void main(String[] args) {
14        Path path = Path.of("images/photo.backup.jpg");
15        System.out.println(baseName(path));
16    }
17}

This keeps path handling and string handling separate, which makes the code easier to test.

Use a Library if You Already Depend on One

If your project already includes Apache Commons IO, FilenameUtils.getBaseName is a reasonable convenience:

java
1import org.apache.commons.io.FilenameUtils;
2
3String base = FilenameUtils.getBaseName("/tmp/reports/summary.csv");
4System.out.println(base);

That is useful when you want a well-known utility method and the dependency is already part of the codebase. It is usually not worth adding a library solely for this one operation.

Decide How to Treat Edge Cases

Not every dot means "there is an extension". For example, Unix-style hidden files such as .gitignore begin with a dot but do not necessarily have a base name plus extension in the usual sense. That is why the helper above returns the whole string when the dot is at position 0.

You should also decide what "archive.tar.gz" means in your application. Some systems want only "gz" removed, while others treat "tar.gz" as a compound extension. The standard lastIndexOf approach removes only the final suffix, which is the safest default unless your domain needs special rules.

Common Pitfalls

One frequent mistake is operating on the full path string and accidentally cutting at a dot in a directory name. Extract the filename first, then strip the extension.

Another issue is mishandling hidden files such as .env or .gitignore. If you remove everything before the first dot, you can end up with an empty string instead of the original filename.

People also assume there is always exactly one dot. Files with multiple dots, or no dot at all, need explicit behavior rather than guesswork.

Finally, decide whether you want to remove only the last extension or every suffix. Those are different requirements, and the implementation should match the one you actually need.

Summary

  • Extract the filename from the path before stripping the extension.
  • Use lastIndexOf('.') to remove the final extension in plain Java.
  • Treat hidden files and extensionless files deliberately instead of assuming every dot is a separator.
  • Decide whether multi-part names such as "archive.tar.gz" should lose one suffix or several.
  • Use a library helper only if it fits the existing dependencies and code style of the project.

Course illustration
Course illustration

All Rights Reserved.