Java
String manipulation
file handling
programming
coding tips

How do I trim a file extension from a String in Java?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Removing a file extension from a Java string looks trivial until you hit edge cases such as names with multiple dots, paths that contain directories, or hidden files that begin with a dot. The safest solution depends on whether you are handling a plain filename or a full path.

For a plain filename, the usual approach is to find the last dot and remove everything after it. The important part is deciding which dots actually represent an extension.

Basic Approach with lastIndexOf

For most filenames, the simplest working solution is to trim everything after the last dot:

java
1public class Main {
2    public static String removeExtension(String name) {
3        int dot = name.lastIndexOf('.');
4        return dot == -1 ? name : name.substring(0, dot);
5    }
6
7    public static void main(String[] args) {
8        System.out.println(removeExtension("report.pdf"));
9        System.out.println(removeExtension("archive.tar.gz"));
10        System.out.println(removeExtension("README"));
11    }
12}

This prints report, archive.tar, and README. For many applications, that behavior is exactly right.

Handle Hidden Files and Paths Correctly

The naive version treats any dot as an extension separator. That breaks for Unix-style hidden files such as .gitignore, where the leading dot is part of the name, not an extension.

It also helps to avoid trimming dots that appear in directory names. This version handles both concerns for a path-like string:

java
1public class Main {
2    public static String removeExtension(String path) {
3        int slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
4        int dot = path.lastIndexOf('.');
5
6        if (dot == -1 || dot <= slash + 1) {
7            return path;
8        }
9
10        return path.substring(0, dot);
11    }
12
13    public static void main(String[] args) {
14        System.out.println(removeExtension("notes.txt"));
15        System.out.println(removeExtension("/tmp/archive.tar.gz"));
16        System.out.println(removeExtension("/home/user/.gitignore"));
17    }
18}

Now .gitignore stays unchanged, while ordinary extensions are removed.

Decide What “Extension” Means in Your App

There is no single universal rule for compound names such as archive.tar.gz. Some programs consider only gz to be the extension. Others treat tar.gz as a meaningful combined extension.

If you want to remove only the last segment, lastIndexOf('.') is correct. If you want to strip a known compound suffix, test for that suffix explicitly:

java
1public class Main {
2    public static String removeKnownCompressedSuffix(String name) {
3        if (name.endsWith(".tar.gz")) {
4            return name.substring(0, name.length() - ".tar.gz".length());
5        }
6        return name;
7    }
8
9    public static void main(String[] args) {
10        System.out.println(removeKnownCompressedSuffix("archive.tar.gz"));
11    }
12}

That is more explicit and easier to maintain than trying to infer every special case from dots alone.

Avoid Overcomplicating It

You do not need regular expressions for the common case. String slicing is clearer, faster to read, and easier to debug. Reach for a library helper only if your project already depends on one and the helper matches your filename rules.

The critical design step is writing down the behavior you want for no-extension files, hidden files, compound suffixes, and full paths.

Common Pitfalls

  • Removing everything after the first dot instead of the last one.
  • Treating .gitignore as if it had an extension.
  • Forgetting that path separators can appear before the final filename dot.
  • Assuming tar.gz should always be removed as one combined suffix.
  • Using a regex for a simple substring operation and making the logic harder to test.

Summary

  • The normal Java solution is to use lastIndexOf('.') and substring.
  • Hidden files and full paths need extra checks so that non-extension dots are preserved.
  • Decide whether your app treats compound names such as tar.gz as one suffix or two.
  • Simple string logic is usually clearer than a regular expression.
  • Define the edge-case behavior first, then implement the smallest method that matches it.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.