谁能告诉我如何在没有扩展名的情况下获取文件名? 例子:
fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
谁能告诉我如何在没有扩展名的情况下获取文件名? 例子:
fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
当前回答
com.google.common.io.Files
档案getNameWithoutExtension sourceFile。getName()。
能胜任一份工作吗
其他回答
以下是来自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("."));
}
给定String文件名,你可以这样做:
String filename = "test.xml";
filename.substring(0, filename.lastIndexOf(".")); // Output: test
filename.split("\\.")[0]; // Output: test
流利的方式:
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);
}
使用FilenameUtils。removeExtension from Apache Commons IO
例子:
您可以提供完整的路径名称,也可以只提供文件名。
String myString1 = FilenameUtils.removeExtension("helloworld.exe"); // returns "helloworld"
String myString2 = FilenameUtils.removeExtension("/home/abc/yey.xls"); // returns "yey"
希望这能有所帮助。