(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 f
It's actually very easy, assuming that you have a valid filename.
In Windows filenames the dot character is only used to designate an extension. So strip off the dot and anything after it.
In unix-like filenames the dot indicates an extension if it's after the last separator ('/') and has at least one character between it and the last separator (and is not the first character, if there are no separators). Find the last dot, see if it satisfies the conditions, and strip it and any trailing characters if it does.
It's important that you validate the filename before you do this, as this algorithm on an invlaid filename might do something unexpected and generate a valid filename. So in Windows you may need to check that there isn't a backslash, or a colon, after the dot.
If you don't know what kind of filename you are dealing with, treating them all like Unix will get you most of the way.
I know a regex to do it, but in Java do i have to write like 10 lines of code to do a simple regex substitution?
With and without killing hidden files:
^(.*)\..*$
^(..*)\..*$
int p=name.lastIndexOf('.');
if (p>0)
name=name.substring(0,p);
I said "p>0" instead of "p>=0" because if the first character is a period we presumably do not want to wipe out the entire name, as in your ".hidden" example.
Do you want to actually update the file name on the disk or are you talking about just manipulating it internally?
The remove()
function above should be rewritten to support test cases like LOST.DIR/myfile.txt
public static String removeExtension( String in )
{
int p = in.lastIndexOf(".");
if ( p < 0 )
return in;
int d = in.lastIndexOf( File.separator );
if ( d < 0 && p == 0 )
return in;
if ( d >= 0 && d > p )
return in;
return in.substring( 0, p );
}
filename.replace("$(.+)\.\\w+", "\1");
Use new Remover().remove(String),
jdb@Vigor14:/tmp/stackoverflow> javac Remover.java && java Remover
folder > folder
hello.txt > hello
read.me > read
hello.bkp.txt > hello.bkp
weird..name > weird.
.hidden > .hidden
Remover.java,
import java.util.*;
public class Remover {
public static void main(String [] args){
Map<String, String> tests = new LinkedHashMap<String, String>();
tests.put("folder", "folder");
tests.put("hello.txt", "hello");
tests.put("read.me", "read");
tests.put("hello.bkp.txt", "hello.bkp");
tests.put("weird..name", "weird.");
tests.put(".hidden", ".hidden");
Remover r = new Remover();
for(String in: tests.keySet()){
String actual = r.remove(in);
log(in+" > " +actual);
String expected = tests.get(in);
if(!expected.equals(actual)){
throw new RuntimeException();
}
}
}
private static void log(String s){
System.out.println(s);
}
public String remove(String in){
if(in == null) {
return null;
}
int p = in.lastIndexOf(".");
if(p <= 0){
return in;
}
return in.substring(0, p);
}
}