java file 不带扩展名,如何获取没有Java扩展名的File对象的名称?

I am trying to get name of a File object without its extension, e.g. getting "vegetation" when the filename is "vegetation.txt." I have tried implementing this code:

openFile = fileChooser.getSelectedFile();

String[] tokens = openFile.getName().split(".");

String name = tokens[0];

Unfortunately, it returns a null object. There is a problem just in the defining the String object, I guess, because the method getName() works correctly; it gives me the name of the file with its extension.

Do you have any idea?

解决方案

If you want to implement this yourself, try this:

String name = file.getName();

int pos = name.lastIndexOf(".");

if (pos > 0) {

name = name.substring(0, pos);

}

(This variation doesn't leave you with an empty string for an input filename like ".txt". If you want the string to be empty in that case, change > 0 to >= 0.)

You could replace the if statement with an assignment using a conditional expression, if you thought it made your code more readable; see @Steven's answer for example. (I don't think it does ... but it is a matter of opinion.)

It is arguably a better idea to use an implementation that someone else has written and tested. Apache FilenameUtils is a good choice; see @slachnick's Answer, and also the linked Q&A.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值