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

how to remove extension from string in java
how to separate filename and extension in java
get file name without extension java
java get file extension
java change file extension
validate file extension in java
java file
how to check multiple file extension in java

What's the most efficient way to trim the suffix in Java, like this:

title part1.txt
title part2.html
=>
title part1
title part2

This is the sort of code that we shouldn't be doing ourselves. Use libraries for the mundane stuff, save your brain for the hard stuff.

In this case, I recommend using FilenameUtils.removeExtension() from Apache Commons IO

Removing the extension from a filename, Your code can be improved in few lines: String fileName = file.getName(); if (​fileName.indexOf(".") > 0) fileName = fileName.substring(0,  Take for example the following path: Using the one-liner will result in: That's incorrect. The result should have been c, but since the file lacked an extension, but the path had a directory with a . in the name, the one-liner method was tricked into giving part of the path as the filename, which is not correct.

str.substring(0, str.lastIndexOf('.'))

Remove file extension, Remove file extension Tag(s): IO. public static String removeExtension(String fileName) { int extPos = fileName.lastIndexOf("."); if(extPos == -1) { return fileName; }  How do I trim a file extension from a String in How do I trim a file extension from a String in Java? 0 votes . 1 view. asked Oct 28, 2019 in Java by Anvi (10.2k

As using the String.substring and String.lastIndex in a one-liner is good, there are some issues in terms of being able to cope with certain file paths.

Take for example the following path:

a.b/c

Using the one-liner will result in:

a

That's incorrect.

The result should have been c, but since the file lacked an extension, but the path had a directory with a . in the name, the one-liner method was tricked into giving part of the path as the filename, which is not correct.

Need for checks

Inspired by skaffman's answer, I took a look at the FilenameUtils.removeExtension method of the Apache Commons IO.

In order to recreate its behavior, I wrote a few tests the new method should fulfill, which are the following:

Path                  Filename
--------------        --------
a/b/c                 c
a/b/c.jpg             c
a/b/c.jpg.jpg         c.jpg

a.b/c                 c
a.b/c.jpg             c
a.b/c.jpg.jpg         c.jpg

c                     c
c.jpg                 c
c.jpg.jpg             c.jpg

(And that's all I've checked for -- there probably are other checks that should be in place that I've overlooked.)

The implementation

The following is my implementation for the removeExtension method:

public static String removeExtension(String s) {

    String separator = System.getProperty("file.separator");
    String filename;

    // Remove the path upto the filename.
    int lastSeparatorIndex = s.lastIndexOf(separator);
    if (lastSeparatorIndex == -1) {
        filename = s;
    } else {
        filename = s.substring(lastSeparatorIndex + 1);
    }

    // Remove the extension.
    int extensionIndex = filename.lastIndexOf(".");
    if (extensionIndex == -1)
        return filename;

    return filename.substring(0, extensionIndex);
}

Running this removeExtension method with the above tests yield the results listed above.

The method was tested with the following code. As this was run on Windows, the path separator is a \ which must be escaped with a \ when used as part of a String literal.

System.out.println(removeExtension("a\\b\\c"));
System.out.println(removeExtension("a\\b\\c.jpg"));
System.out.println(removeExtension("a\\b\\c.jpg.jpg"));

System.out.println(removeExtension("a.b\\c"));
System.out.println(removeExtension("a.b\\c.jpg"));
System.out.println(removeExtension("a.b\\c.jpg.jpg"));

System.out.println(removeExtension("c"));
System.out.println(removeExtension("c.jpg"));
System.out.println(removeExtension("c.jpg.jpg"));

The results were:

c
c
c.jpg
c
c
c.jpg
c
c
c.jpg

The results are the desired results outlined in the test the method should fulfill.

How do I trim a file extension from a String in Java?, This is the sort of code that we shouldn't be doing ourselves. Use libraries for the mundane stuff, save your brain for the hard stuff. In this case, I recommend  How can we trim a file extension from a String in Java? pandi Asked on October 26, 2018 in Windows. Share ; Comment(0) Add Comment. Add comment

BTW, in my case, when I wanted a quick solution to remove a specific extension, this is approximately what I did:

  if (filename.endsWith(ext))
    return filename.substring(0,filename.length() - ext.length());
  else
    return filename;

How to Remove Extension from Filename in Java, The following function removes extension from a filename using Java. However it will not modify the hidden file names in mac/linux which starts with a dot  The java lang.string.trim()is a built-in function that eliminates leading and trailing spaces.The Unicode value of space character is ‘\u0020’. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.

String foo = "title part1.txt";
foo = foo.substring(0, foo.lastIndexOf('.'));

remove extension from file name (Java in General forum at , Hi All, I can get the name of a file using getName(), but I want to remove the extension. Should I just write a substring to extract a filename, or is  Java - String trim() Method - This method returns a copy of the string, with leading and trailing whitespace omitted.

How to Get the File Extension of a File in Java, and if a filename consists of the extension only, such as .gitignore or .DS_Store. 2.1. Simple String Handling Approach. Java String trim() The java string trim() method eliminates leading and trailing spaces. The unicode value of space character is '\u0020'. The trim() method in java string checks this unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.

Remove Extension from a file name in C#, In this post, we will see how to remove extension from a file name in C#. GetExtension method and remove the same characters from end of the string as length Please use our online compiler to post code in comments using C, C++, Java,  If it exists, then it will find the last position of the dot ‘.' and return the characters after that, the characters after the last dot ‘.' known as the file extension. Special Cases: No extension – this method will return an empty String; Only extension – this method will return the String after the dot, e.g. “gitignore” 2.2.

How to remove extension from string in PHP?, When an extension of file is known it can be passed as a parameter to basename function to tell it to remove that extension from the filename. Example:. (Without including any external libraries.) What's the most efficient way to remove the extension of a filename in Java, without assuming anything of the filename? Some examples and expected resu

Comments
  • efficient code wise, is what you mean i hope, not CPU wise
  • He wasn't asking how to do it, he was asking what's the most efficient way. I came here looking for the same thing.
  • Absolutely bang on.
  • For 95% of the projects, this should be the accepted answer. Rewriting code like this is the root cause for many headaches!
  • Just add the following line in gradle to add the depedency:- compile 'commons-io:commons-io:2.6'
  • example please.
  • If you have Apache Commons I/O already in your project, that's right. But if this all you need from it, you're adding (at least) 2.5 MB of dead weight to your project for something that can be easily done with a single line.
  • This should be assigned to a new variable as str is not modified.
  • Handle with care: it'll throw an Exception at you if the file name has no suffix.
  • what about archive.tar.bz2 ?
  • if(str.contains(".")) str.substring(0, str.lastIndexOf('.'))
  • if(str != null && str.contains(".")) str.substring(0, str.lastIndexOf('.')). FilenameUtils is another dependency, and not always available
  • Great answer. Is there a particular reason why you use System.getProperty("file.separator") and not just File.separator?