Java:将文件名拆分为基本文件名和扩展名
有没有比之类的更好的方法来获取文件基名和扩展名
Is there a better way to get file basename and extension than something like
File f = ...
String name = f.getName();
int dot = name.lastIndexOf('.');
String base = (dot == -1) ? name : name.substring(0, dot);
String extension = (dot == -1) ? "" : name.substring(dot+1);
我知道其他人提到了 String.split
,但这里有一个变体,它只产生 两个 标记(基础和扩展):
I know others have mentioned String.split
, but here is a variant that only yields two tokens (the base and the extension):
String[] tokens = fileName.split("\.(?=[^\.]+$)");
例如:
"test.cool.awesome.txt".split("\.(?=[^\.]+$)");
产量:
["test.cool.awesome", "txt"]
正则表达式告诉 Java 在任何句点之后进行拆分,然后是任意数量的非句点,然后是输入的结尾.只有一个句点符合这个定义(即最后句点).
The regular expression tells Java to split on any period that is followed by any number of non-periods, followed by the end of input. There is only one period that matches this definition (namely, the last period).
技术上 从正则上来说,这种技术被称为 零宽度正向预测.
Technically Regexically speaking, this technique is called zero-width positive lookahead.
顺便说一句,如果您想拆分路径并获取完整的文件名,包括但不限于点扩展名,请使用带正斜杠的路径,
BTW, if you want to split a path and get the full filename including but not limited to the dot extension, using a path with forward slashes,
String[] tokens = dir.split(".+?/(?=[^/]+$)");
例如:
String dir = "/foo/bar/bam/boozled";
String[] tokens = dir.split(".+?/(?=[^/]+$)");
// [ "/foo/bar/bam/" "boozled" ]