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

查看:113
本文介绍了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,如果要拆分路径获取完整的文件名,包括但不限于点扩展名,使用带有斜杠的路径,

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天全站免登陆