谁能告诉我如何在没有扩展名的情况下获取文件名? 例子:
fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
谁能告诉我如何在没有扩展名的情况下获取文件名? 例子:
fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
当前回答
com.google.common.io.Files
档案getNameWithoutExtension sourceFile。getName()。
能胜任一份工作吗
其他回答
public static String getFileExtension(String fileName) {
if (TextUtils.isEmpty(fileName) || !fileName.contains(".") || fileName.endsWith(".")) return null;
return fileName.substring(fileName.lastIndexOf(".") + 1);
}
public static String getBaseFileName(String fileName) {
if (TextUtils.isEmpty(fileName) || !fileName.contains(".") || fileName.endsWith(".")) return null;
return fileName.substring(0,fileName.lastIndexOf("."));
}
如果你像我一样,宁愿使用一些库代码,他们可能已经考虑了所有的特殊情况,比如如果你在路径中传递null或圆点,而不是在文件名中,会发生什么,你可以使用以下方法:
import org.apache.commons.io.FilenameUtils;
String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt);
最简单的方法是使用正则表达式。
fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");
上面的表达式将删除最后一个点后面跟一个或多个字符。这是一个基本的单元测试。
public void testRegex() {
assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", ""));
assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", ""));
}
你可以使用java split函数从扩展名中分离文件名,如果你确定文件名中只有一个用于扩展名的点。
文件文件名=新文件('test.txt'); File.getName () .split(“[]”);
因此拆分[0]将返回test拆分[1]将返回txt
简单起见,使用Java的String.replaceAll()方法,如下所示:
String fileNameWithExt = "test.xml";
String fileNameWithoutExt
= fileNameWithExt.replaceAll( "^.*?(([^/\\\\\\.]+))\\.[^\\.]+$", "$1" );
当filenamewitheext包含完全限定路径时,这也可以工作。