Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove filename extension in Java

Tags:

(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 results:

  • folder > folder
  • hello.txt > hello
  • read.me > read
  • hello.bkp.txt > hello.bkp
  • weird..name > weird.
  • .hidden > .hidden

(or should the last one be just hidden?)

Edit: The original question assumed that the input is a filename (not a file path). Since some answers are talking about file paths, such functions should also work in cases like:

  • rare.folder/hello > rare.folder/hello

This particular case is handled very well by Sylvain M's answer.

like image 656
hpique Avatar asked Aug 10 '10 13:08

hpique


1 Answers

Using common io from apache http://commons.apache.org/io/

public static String removeExtension(String filename)

FYI, the source code is here:

http://commons.apache.org/proper/commons-io/javadocs/api-release/src-html/org/apache/commons/io/FilenameUtils.html#line.1025

Arg, I've just tried something...

System.out.println(FilenameUtils.getExtension(".polop")); // polop System.out.println(FilenameUtils.removeExtension(".polop")); // empty string 

So, this solution seems to be not very good... Even with common io, you'll have to play with removeExtension() getExtension() indexOfExtension()...

like image 132
sly7_7 Avatar answered Oct 14 '22 13:10

sly7_7