Can anyone tell me how to get file name without the extension? Example:
fileNameWithExt = test.xml;
fileNameWithOutExt = test;
Can anyone tell me how to get file name without the extension? Example:
fileNameWithExt = test.xml;
fileNameWithOutExt = test;
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
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("[.][^.]+$", ""));
}
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);