(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.
I’m going to have a stab at this that uses the two-arg version of
lastIndexOfin order to remove some special-case checking code, and hopefully make the intention more readable. Credit goes to Justin ‘jinguy’ Nelson for providing the basis of this method:To me this is clearer than special-casing hidden files and files that don’t contain a dot. It also reads clearer to what I understand your specification to be; something like “remove the last dot and everything following it, assuming it exists and is not the first character of the filename”.
Note that this example also implies Strings as inputs and outputs. Since most of the abstraction requires
Fileobjects, it would be marginally clearer if those were the inputs and outputs as well.