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

JavaStringProcess

Java Problem Overview


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

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

Java Solutions


Solution 1 - 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 using FilenameUtils.removeExtension() from Apache Commons IO

Solution 2 - Java

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

Solution 3 - Java

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.

Solution 4 - Java

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;

Solution 5 - Java

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

Solution 6 - Java

you can try this function , very basic

public String getWithoutExtension(String fileFullPath){
    return fileFullPath.substring(0, fileFullPath.lastIndexOf('.'));
}

Solution 7 - Java

String fileName="foo.bar";
int dotIndex=fileName.lastIndexOf('.');
if(dotIndex>=0) { // to prevent exception if there is no dot
  fileName=fileName.substring(0,dotIndex);
}

Is this a trick question? :p

I can't think of a faster way atm.

Solution 8 - Java

Use a method in com.google.common.io.Files class if your project is already dependent on Google core library. The method you need is getNameWithoutExtension.

Solution 9 - Java

I found https://stackoverflow.com/questions/941272/how-do-i-trim-a-file-extension-from-a-string-in-java/990492#990492">coolbird's answer particularly useful.

But I changed the last result statements to:

if (extensionIndex == -1)
return s;




return s.substring(0, lastSeparatorIndex+1)
+ filename.substring(0, extensionIndex);

return s.substring(0, lastSeparatorIndex+1) + filename.substring(0, extensionIndex);

as I wanted the full path name to be returned.

So "C:\Users\mroh004.COM\Documents\Test\Test.xml" becomes
"C:\Users\mroh004.COM\Documents\Test\Test" and not
"Test"

Solution 10 - Java

filename.substring(filename.lastIndexOf('.'), filename.length()).toLowerCase();

Solution 11 - Java

Use a regex. This one replaces the last dot, and everything after it.

String baseName = fileName.replaceAll("\\.[^.]*$", "");

You can also create a Pattern object if you want to precompile the regex.

Solution 12 - Java

If you use Spring you could use

org.springframework.util.StringUtils.stripFilenameExtension(String path)

> Strip the filename extension from the given Java resource path, e.g. > > "mypath/myfile.txt" -> "mypath/myfile". > > Params: path – the file path > > Returns: the path with stripped filename extension

Solution 13 - Java

 private String trimFileExtension(String fileName)
  {
	 String[] splits = fileName.split( "\\." );
	 return StringUtils.remove( fileName, "." + splits[splits.length - 1] );
  }

Solution 14 - Java

String[] splitted = fileName.split(".");
String fileNameWithoutExtension = fileName.replace("." + splitted[splitted.length - 1], "");

Solution 15 - Java

create a new file with string image path

String imagePath;
File test = new File(imagePath);
test.getName();
test.getPath();
getExtension(test.getName());


public static String getExtension(String uri) {
        if (uri == null) {
            return null;
        }

        int dot = uri.lastIndexOf(".");
        if (dot >= 0) {
            return uri.substring(dot);
        } else {
            // No extension.
            return "";
        }
    }

Solution 16 - Java

org.apache.commons.io.FilenameUtils version 2.4 gives the following answer

public static String removeExtension(String filename) {
    if (filename == null) {
        return null;
    }
    int index = indexOfExtension(filename);
    if (index == -1) {
        return filename;
    } else {
        return filename.substring(0, index);
    }
}

public static int indexOfExtension(String filename) {
    if (filename == null) {
        return -1;
    }
    int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR);
    int lastSeparator = indexOfLastSeparator(filename);
    return lastSeparator > extensionPos ? -1 : extensionPos;
}

public static int indexOfLastSeparator(String filename) {
    if (filename == null) {
        return -1;
    }
    int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR);
    int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR);
    return Math.max(lastUnixPos, lastWindowsPos);
}

public static final char EXTENSION_SEPARATOR = '.';
private static final char UNIX_SEPARATOR = '/';
private static final char WINDOWS_SEPARATOR = '\\';

Solution 17 - Java

The best what I can write trying to stick to the Path class:

Path removeExtension(Path path) {
    return path.resolveSibling(path.getFileName().toString().replaceFirst("\\.[^.]*$", ""));
}

Solution 18 - Java

I would do like this:

String title_part = "title part1.txt";
int i;
for(i=title_part.length()-1 ; i>=0 && title_part.charAt(i)!='.' ; i--);
title_part = title_part.substring(0,i);

Starting to the end till the '.' then call substring.

Edit: Might not be a golf but it's effective :)

Solution 19 - Java

Keeping in mind the scenarios where there is no file extension or there is more than one file extension

example Filename : file | file.txt | file.tar.bz2

/**
 *
 * @param fileName
 * @return file extension
 * example file.fastq.gz => fastq.gz
 */
private String extractFileExtension(String fileName) {
    String type = "undefined";
    if (FilenameUtils.indexOfExtension(fileName) != -1) {
        String fileBaseName = FilenameUtils.getBaseName(fileName);
        int indexOfExtension = -1;
        while (fileBaseName.contains(".")) {
            indexOfExtension = FilenameUtils.indexOfExtension(fileBaseName);
            fileBaseName = FilenameUtils.getBaseName(fileBaseName);
        }
        type = fileName.substring(indexOfExtension + 1, fileName.length());
    }
    return type;
}

Solution 20 - Java

String img = "example.jpg";
// String imgLink = "http://www.example.com/example.jpg";
URI uri = null;

try {
    uri = new URI(img);
    String[] segments = uri.getPath().split("/");
    System.out.println(segments[segments.length-1].split("\\.")[0]);
} catch (Exception e) {
    e.printStackTrace();
}

This will output example for both img and imgLink

Solution 21 - Java

public static String removeExtension(String file) {
	if(file != null && file.length() > 0) {
		while(file.contains(".")) {
			file = file.substring(0, file.lastIndexOf('.'));
		}
	}
	return file;
}

Solution 22 - Java

private String trimFileName(String fileName)
    {
        String[] ext;
        ext = fileName.split("\\.");
        
        return fileName.replace(ext[ext.length - 1], "");

    }

This code will spilt the file name into parts where ever it has " . ", For eg. If the file name is file-name.hello.txt then it will be spilted into string array as , { "file-name", "hello", "txt" }. So anyhow the last element in this string array will be the file extension of that particular file , so we can simply find the last element of any arrays with arrayname.length - 1, so after we get to know the last element, we can just replace the file extension with an empty string in that file name. Finally this will return file-name.hello. , if you want to remove also the last period then you can add the string with only period to the last element of string array in the return line. Which should look like,

return fileName.replace("." +  ext[ext.length - 1], "");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionomgView Question on Stackoverflow
Solution 1 - JavaskaffmanView Answer on Stackoverflow
Solution 2 - JavaSvitlana MaksymchukView Answer on Stackoverflow
Solution 3 - JavacoobirdView Answer on Stackoverflow
Solution 4 - JavaEdward FalkView Answer on Stackoverflow
Solution 5 - JavaJhericoView Answer on Stackoverflow
Solution 6 - JavaShantonuView Answer on Stackoverflow
Solution 7 - JavaHuxiView Answer on Stackoverflow
Solution 8 - JavaTobyView Answer on Stackoverflow
Solution 9 - JavamxroView Answer on Stackoverflow
Solution 10 - JavaAlexanderView Answer on Stackoverflow
Solution 11 - JavaSteven SpunginView Answer on Stackoverflow
Solution 12 - JavaWolf359View Answer on Stackoverflow
Solution 13 - JavasupernovaView Answer on Stackoverflow
Solution 14 - JavaMahdakView Answer on Stackoverflow
Solution 15 - JavaPravin BhosaleView Answer on Stackoverflow
Solution 16 - JavaSomeone SomewhereView Answer on Stackoverflow
Solution 17 - JavaDavid L.View Answer on Stackoverflow
Solution 18 - JavafmsfView Answer on Stackoverflow
Solution 19 - JavaChoesangView Answer on Stackoverflow
Solution 20 - Javaurs86roView Answer on Stackoverflow
Solution 21 - JavaAlexeyView Answer on Stackoverflow
Solution 22 - JavaViknesh TPKView Answer on Stackoverflow