谁能告诉我如何在没有扩展名的情况下获取文件名? 例子:
fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
谁能告诉我如何在没有扩展名的情况下获取文件名? 例子:
fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
当前回答
从相对路径或完整路径获取名称的最简单方法是使用
进口org.apache.commons.io.FilenameUtils; FilenameUtils.getBaseName (definitionFilePath)
其他回答
你可以使用java split函数从扩展名中分离文件名,如果你确定文件名中只有一个用于扩展名的点。
文件文件名=新文件('test.txt'); File.getName () .split(“[]”);
因此拆分[0]将返回test拆分[1]将返回txt
请看下面的测试程序:
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
最简单的方法是使用正则表达式。
fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");
上面的表达式将删除最后一个点后面跟一个或多个字符。这是一个基本的单元测试。
public void testRegex() {
assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", ""));
assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", ""));
}
对于Kotlin来说,它现在很简单:
val fileNameStr = file.nameWithoutExtension
流利的方式:
public static String fileNameWithOutExt (String fileName) {
return Optional.of(fileName.lastIndexOf(".")).filter(i-> i >= 0)
.filter(i-> i > fileName.lastIndexOf(File.separator))
.map(i-> fileName.substring(0, i)).orElse(fileName);
}