谁能告诉我如何在没有扩展名的情况下获取文件名? 例子:
fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
谁能告诉我如何在没有扩展名的情况下获取文件名? 例子:
fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
当前回答
这是根据我的喜好排列的综合清单。
使用apache commons
import org.apache.commons.io.FilenameUtils;
String fileNameWithoutExt = FilenameUtils.getBaseName(fileName);
OR
String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);
使用谷歌番石榴(如果你已经在使用)
import com.google.common.io.Files;
String fileNameWithOutExt = Files.getNameWithoutExtension(fileName);
Files.getNameWithoutExtension
或者使用Core Java
1)
String fileName = file.getName();
int pos = fileName.lastIndexOf(".");
if (pos > 0 && pos < (fileName.length() - 1)) { // If '.' is not the first or last character.
fileName = fileName.substring(0, pos);
}
if (fileName.indexOf(".") > 0) {
return fileName.substring(0, fileName.lastIndexOf("."));
} else {
return fileName;
}
private static final Pattern ext = Pattern.compile("(?<=.)\\.[^.]+$");
public static String getFileNameWithoutExtension(File file) {
return ext.matcher(file.getName()).replaceAll("");
}
生命之光接口
import com.liferay.portal.kernel.util.FileUtil;
String fileName = FileUtil.stripExtension(file.getName());
其他回答
从相对路径或完整路径获取名称的最简单方法是使用
进口org.apache.commons.io.FilenameUtils; FilenameUtils.getBaseName (definitionFilePath)
以下是来自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 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("."));
}
你可以使用java split函数从扩展名中分离文件名,如果你确定文件名中只有一个用于扩展名的点。
文件文件名=新文件('test.txt'); File.getName () .split(“[]”);
因此拆分[0]将返回test拆分[1]将返回txt
如果你像我一样,宁愿使用一些库代码,他们可能已经考虑了所有的特殊情况,比如如果你在路径中传递null或圆点,而不是在文件名中,会发生什么,你可以使用以下方法:
import org.apache.commons.io.FilenameUtils;
String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt);