谁能告诉我如何在没有扩展名的情况下获取文件名? 例子:
fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
谁能告诉我如何在没有扩展名的情况下获取文件名? 例子:
fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
当前回答
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("."));
}
其他回答
请看下面的测试程序:
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
仅限文件名,其中还包括完整路径。不需要外部库,正则表达式等等
public class MyClass {
public static void main(String args[]) {
String file = "some/long/directory/blah.x.y.z.m.xml";
System.out.println(file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf(".")));
//outputs blah.x.y.z.m
}
}
最简单的方法是使用正则表达式。
fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");
上面的表达式将删除最后一个点后面跟一个或多个字符。这是一个基本的单元测试。
public void testRegex() {
assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", ""));
assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", ""));
}
试试下面的代码。使用核心Java基本函数。它负责处理有扩展名的字符串和没有扩展名的字符串(没有'。'字符)。多重'的情况。也有。
String str = "filename.xml";
if (!str.contains("."))
System.out.println("File Name=" + str);
else {
str = str.substring(0, str.lastIndexOf("."));
// Because extension is always after the last '.'
System.out.println("File Name=" + str);
}
您可以调整它来处理空字符串。
如果你像我一样,宁愿使用一些库代码,他们可能已经考虑了所有的特殊情况,比如如果你在路径中传递null或圆点,而不是在文件名中,会发生什么,你可以使用以下方法:
import org.apache.commons.io.FilenameUtils;
String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt);