Java:将文件名拆分为基本文件名和扩展名 [英] Java: splitting the filename into a base and extension

查看:52
本文介绍了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" ] 

这篇关于Java:将文件名拆分为基本文件名和扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆