0

Possible Duplicate:
How to get file name without the extension?

I have a list of xml files and I'm trying to return just the file name without the extension. For example, if I have:

String filename = "hello.xml";

How would I return just "hello" with the fact the file names vary?

4

3 回答 3

2
String filenameSansExt = filename.replaceAll("\\.[^.]*", "");
于 2013-01-13T01:41:53.810 回答
1

使用substring()比使用replaceAll()正则表达式或任何其他正则表达式更有效。

两个答案都不太令人满意:

  • 正则表达式太慢,但正确
  • lastIndexOf()'.'不存在时会抛出异常(索引-1

正确答案必须检查索引lastIndexOf()

于 2013-01-13T01:50:54.937 回答
-1

您可以在 java 中对字符串使用 substring 函数。您将从 0(字符串的开头)开始并在第 4 个到最后一个字符(“。”)之前结束

String filename = "hello.xml";
String filename2 = filename.substring(0, filename.length() - 4);
于 2013-01-13T01:47:58.987 回答