谁能告诉我如何在没有扩展名的情况下获取文件名? 例子:
fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
谁能告诉我如何在没有扩展名的情况下获取文件名? 例子:
fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
当前回答
以下是来自https://android.googlesource.com/platform/tools/tradefederation/+/master/src/com/android/tradefed/util/FileUtil.java的参考资料
/**
* 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);
}
}
其他回答
请看下面的测试程序:
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
从相对路径或完整路径获取名称的最简单方法是使用
进口org.apache.commons.io.FilenameUtils; FilenameUtils.getBaseName (definitionFilePath)
给定String文件名,你可以这样做:
String filename = "test.xml";
filename.substring(0, filename.lastIndexOf(".")); // Output: test
filename.split("\\.")[0]; // Output: test
使用FilenameUtils。removeExtension from Apache Commons IO
例子:
您可以提供完整的路径名称,也可以只提供文件名。
String myString1 = FilenameUtils.removeExtension("helloworld.exe"); // returns "helloworld"
String myString2 = FilenameUtils.removeExtension("/home/abc/yey.xls"); // returns "yey"
希望这能有所帮助。
最简单的方法是使用正则表达式。
fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");
上面的表达式将删除最后一个点后面跟一个或多个字符。这是一个基本的单元测试。
public void testRegex() {
assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", ""));
assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", ""));
}