谁能告诉我如何获得不带扩展名的文件名?示例:
fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
发布于 2009-05-29 05:31:42
最简单的方法是使用正则表达式。
fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");
上面的表达式将删除后面跟着一个或多个字符的最后一个点。这是一个基本的单元测试。
public void testRegex() {
assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", ""));
assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", ""));
}
发布于 2009-05-29 05:27:24
请参阅以下测试程序:
public class javatemp {
static String stripExtension (String str) {
// Handle null case specially.
if (str == null) return null;
// Get position of last '.'.
int pos = str.lastIndexOf(".");
// If there wasn't any '.' just return the string as is.
if (pos == -1) return str;
// Otherwise return the string, up to the dot.
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."));
}
}
以下哪项输出:
test.xml -> test
test.2.xml -> test.2
test -> test
test. -> test
发布于 2016-07-04 11:36:17
/**
* Gets the base name, without extension, of given file name.
* <p/>
* e.g. getBaseName("file.txt") will return "file"
*
* @param fileName
* @return the base name
*/
public static String getBaseName(String fileName) {
int index = fileName.lastIndexOf('.');
if (index == -1) {
return fileName;
} else {
return fileName.substring(0, index);
}
}
https://stackoverflow.com/questions/924394
复制相似问题