如何在Java中更改运行时的文件扩展名 [英] How to change file extension at runtime in Java

查看:146
本文介绍了如何在Java中更改运行时的文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现压缩和解压缩文件的程序。我想要做的就是将名称为 fileName.zip 文件(fileName.fileExtension)压缩,并在解压缩时再将其更改为 fileName.fileExtension

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));
    }






编辑:John的方法重命名文件(保留扩展名)。要更改扩展名,请执行以下操作:


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);
}

这只会将最后一个扩展名更改为文件名,即 .gz archive.tar.gz 的一部分。因此,它可以正常使用linux隐藏文件,其名称以开头。
这是非常安全的,因为如果 getParent()返回 null (即如果父节点是系统根),它将强制转换为空字符串作为文件的整个参数首先评估构造函数。

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.

唯一可以获得有趣输出的情况是传入表示系统根目录的文件,在这种情况下 null 被添加到路径字符串的其余部分。

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.

这篇关于如何在Java中更改运行时的文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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