java 文件去除扩展名_在Java中删除文件扩展名

为了删除一些特殊情况的检查代码,我将要使用一个stab来使用这两个版本的lastIndexOf,并希望使这个意图更易读。信用额度为

Justin ‘jinguy’ Nelson提供了这种方法的基础:

public static String removeExtention(String filePath) {

// These first few lines the same as Justin's

File f = new File(filePath);

// if it's a directory, don't remove the extention

if (f.isDirectory()) return filePath;

String name = f.getName();

// Now we know it's a file - don't need to do any special hidden

// checking or contains() checking because of:

final int lastPeriodPos = name.lastIndexOf('.');

if (lastPeriodPos <= 0)

{

// No period after first character - return name as it was passed in

return filePath;

}

else

{

// Remove the last period and everything after it

File renamed = new File(f.getParent(), name.substring(0, lastPeriodPos));

return renamed.getPath();

}

}

对我来说,这比特殊套管隐藏的文件和不包含点的文件更清晰。它也更清楚地看到我理解你的规范是什么;像“删除最后一个点和其后的所有内容,假定它存在,而不是文件名的第一个字符”。

请注意,此示例也意味着Strings作为输入和输出。由于大部分抽象需要File对象,所以如果输入和输出也是这样,那么它将会更加清晰。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值