tags:

views:

445

answers:

3

Can anyone tell me how to get file name without the extension? Example:

fileNameWithExt = test.xml;
fileNameWithOutExt = test;
+5  A: 

See the following test program:

public class javatemp {
    static String stripExtension (String str) {
        if (str == null)
            return null;
        int pos = str.lastIndexOf(".");
        if (pos == -1)
            return str;
        return str.substring(0,pos);
    }

    public static void main(String[] args) {
        System.out.println ("test.xml   -> " + stripExtension ("test.xml"));
        System.out.println ("test.2.xml -> " + stripExtension ("test.2.xml"));
        System.out.println ("test       -> " + stripExtension ("test"));
        System.out.println ("test.      -> " + stripExtension ("test."));
    }
}

which outputs:

test.xml   -> test
test.2.xml -> test.2
test       -> test
test.      -> test
paxdiablo
You forgot the null test:System.out.println ("null -> " + stripExtension (null));
Ulf Lindback
As you wish :-)
paxdiablo
A: 

The easiest way is to use a regular expression.

fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");

The above expression will remove the last dot followed by one or more characters. Here's a basic unit test.

public void testRegex() {
 assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", ""));
 assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", ""));
}
brianegge
thanks dude, it works :)
Iso
+4  A: 

If you like me rather use some library code where they probably have thought of all special cases, such what if you pass in null or dots in the path but not in the filename, you can use the following:

import org.apache.commons.io.FilenameUtils;
String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt);
Ulf Lindback
+1 for not reinventing the wheel
skaffman