怎么改java扩展名,如何在Java中更改运行时的文件扩展名

I am trying to implement program to zip and unzip a file. All I want to do is to zip a file (fileName.fileExtension) with name as fileName.zip and on unzipping change it again to fileName.fileExtension.

解决方案

This is how I used to rename files or change its extension.

public static void modify(File file)

{

int index = file.getName().indexOf(".");

//print filename

//System.out.println(file.getName().substring(0, index));

//print extension

//System.out.println(file.getName().substring(index));

String ext = file.getName().substring(index);

//use file.renameTo() to rename the file

file.renameTo(new File("Newname"+ext));

}

edit: John's method renames the file (keeping the extension). To change the extension do:

public static File changeExtension(File f, String newExtension) {

int i = f.getName().lastIndexOf('.');

String name = f.getName().substring(0,i);

return new File(f.getParent() + "/" + name + newExtension);

}

This only changes the last extension to a filename, i.e. the .gz part of archive.tar.gz. Therfore it works fine with linux hidden files, for which the name starts with a .

This is quite safe because if getParent() returns null (i.e. in the event of the parent being the system root) it is "cast" to an empty String as the whole argument to the File constructor is evaluated first.

The only case where you will get a funny output is if you pass in a File representing the system root itself, in which case the null is prepended to the rest of the path string.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值