JAVA SpringBoot zip文件夹重命名

因为项目采用obs文件存储,导致同名文件会被覆盖,所以采用后台根据时间戳重命名的方式,别的文件类型都没有问题,到zip的时候,发现解压后的文件名还是重命名之前的文件名,所以要实现zip文件里面的文件夹也改为新的命名。

一开始的设想是有没有方法能够在不解压的情况下实现,无奈没有找到,有知道的小伙伴可以指点一下。于是只能使用常规的思路,先解压,重命名,再加压的方式。

项目使用zip4j完成解压、加压操作,需要在pom.xml中添加

<dependency>
    <groupId>net.lingala.zip4j</groupId>
    <artifactId>zip4j</artifactId>
    <version>1.3.2</version>
</dependency>

一、文件保存到临时地址

因为项目使用的MultipartFile接受文件,所以要先转为File,并存放到临时地址

String zipName = multipartFile.getOriginalFilename();
String path = getPath();
System.out.println(path);
File file = new File(path + zipName);
System.out.println(file);
if (!file.getParentFile().exists()) {
   file.getParentFile().mkdirs();
}
multipartFile.transferTo(file);

/**
* 获取不同环境文件存放地址
**/
public static String getPath() {
   String env = ProfileUtil.getActiveProfile();
   String path = null;
   if (env.equals("dev")) {
       path = "Windows环境地址";
   } else {
       path = "服务器文件存放地址";
   }
   return path;
}

二、解压

String newFoldel = "自定义新文件名";
ZipFile zFile = new ZipFile(file);
zFile.setFileNameCharset("gbk");
String dest = path + newFoldel;
File destDir = new File(dest);
zFile.extractAll(dest);

三、重命名

file自带的renameTo可以进行重命名文件夹

String orgFoldel = multipartFile.getOriginalFilename().substring(0, multipartFile.getOriginalFilename().lastIndexOf("."));
File file1 = new File((path + newFoldel + "/" + orgFoldel));
file1.renameTo(new File(path + newFoldel + "/" + newFoldel));

四、压缩并转为MultipartFile

ZipFile newZipFile = fastZip(path, newFoldel + ".zip", path + newFoldel);

File newFile = new File(path, newFoldel + ".zip");
FileInputStream fileInputStream = new FileInputStream(newFile);
MultipartFile newMultipartFile = new MockMultipartFile(newFile.getName(), newFile.getName(),
        ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

/**
 * zip4j压缩目录为一个zip包
 * <p>
 * 同一路径多次压缩只会生成一个zip包
 * 返回null表示压缩失败,
 * 返回ZipFile对象表示压缩成功。
 *
 * @param productZipDir    生成的zip包存放路径 (d:\\xxx\\xx\\)
 * @param productZipName   生成的zip包名 (xxx.zip)
 * @param originalDestPath 要压缩的原始目录地址(e:\\xxx\\xx\\)
 * @throws ZipException
 */
public static ZipFile fastZip(String productZipDir, String productZipName, String originalDestPath) throws ZipException {

    if (StringUtils.isEmpty(productZipDir)) {
        return null;
    }
    if (StringUtils.isEmpty(productZipName)) {
        return null;
    }
    if (StringUtils.isEmpty(originalDestPath)) {
        return null;
    }

    //zip包存放路径 不存在则建立
    File productDir = new File(productZipDir);
    if (!productDir.exists()) {
        productDir.mkdirs();
    }

    //要压缩的原始目录地址 不存在则返回null
    File originalPath = new File(originalDestPath);
    if (!originalPath.isDirectory()) {
        return null;
    }
    if (!originalPath.exists()) {
        return null;
    }


    // 生成的压缩文件
    ZipFile zipFile = new ZipFile(productZipDir + productZipName);


    ZipParameters parameters = new ZipParameters();
    // 压缩方式 8
    parameters.setCompressionMethod(8);
    // 压缩级别 5
    parameters.setCompressionLevel(5);
    // 要打包的文件夹
    File currentFile = new File(originalDestPath);
    File[] fs = currentFile.listFiles();
    // 遍历originalDestPath文件夹下所有的文件、文件夹
    for (File f : fs) {
        if (f.isDirectory()) {
            zipFile.addFolder(new File(f.getPath()), parameters);
        } else {
            zipFile.addFile(f, parameters);
        }
    }
    //返回zip包对象
    return zipFile;
}

五、删除临时文件

public static boolean deleteFile(String fileName) {
    File file = new File(fileName);
    // 如果文件路径只有单个文件
    if (file.exists() && file.isFile()) {
        if (file.delete()) {
            System.out.println("删除文件" + fileName + "成功!");
            return true;
        } else {
            System.out.println("删除文件" + fileName + "失败!");
            return false;
        }
    } else {
        System.out.println(fileName + "不存在!");
        return false;
    }
}


public static boolean deleteAllFile(String dir) {
    // 如果dir不以文件分隔符结尾,自动添加文件分隔符
    File dirFile = new File(dir);
    // 如果dir对应的文件不存在,或者不是一个目录,则退出
    if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
        System.out.println("删除文件夹失败:" + dir + "不存在!");
        return false;
    }
    boolean flag = true;
    // 删除文件夹中的所有文件包括子文件夹
    File[] files = dirFile.listFiles();
    for (int i = 0; i < files.length; i++) {
        // 删除子文件
        if (files[i].isFile()) {
            flag = deleteFile(files[i].getAbsolutePath());
            if (!flag)
                break;
        }
        // 删除子文件夹
        else if (files[i].isDirectory()) {
            flag = deleteAllFile(files[i].getAbsolutePath());
            if (!flag)
                break;
        }
    }
    if (!flag) {
        System.out.println("删除文件夹失败!");
        return false;
    }
    // 删除当前文件夹
    if (dirFile.delete()) {
        System.out.println("删除文件夹" + dir + "成功!");
        return true;
    } else {
        return false;
    }
}

六、完整代码

ZipUtils.java

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ZipUtils {
    public static MultipartFile decZip(String apiName, MultipartFile multipartFile) throws IOException, ZipException {
        String zipName = multipartFile.getOriginalFilename();
        String path = getPath();

        System.out.println(path);
        File file = new File(path + zipName);
        System.out.println(file);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        multipartFile.transferTo(file);

        //解压
        String newFoldel = "自定义文件夹名称";
        ZipFile zFile = new ZipFile(file);
        zFile.setFileNameCharset("gbk");
        String dest = path + newFoldel;
        File destDir = new File(dest);
        zFile.extractAll(dest);
        
        //重命名
        String orgFoldel = multipartFile.getOriginalFilename().substring(0, multipartFile.getOriginalFilename().lastIndexOf("."));
        File file1 = new File((path + newFoldel + "/" + orgFoldel));
        file1.renameTo(new File(path + newFoldel + "/" + newFoldel));

        //压缩
        ZipFile newZipFile = fastZip(path, newFoldel + ".zip", path + newFoldel);
        File newFile = new File(path, newFoldel + ".zip");
        FileInputStream fileInputStream = new FileInputStream(newFile);
        MultipartFile newMultipartFile = new MockMultipartFile(newFile.getName(), newFile.getName(),
                ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        return newMultipartFile;
    }

    /**
     * zip4j压缩目录为一个zip包
     * <p>
     * 同一路径多次压缩只会生成一个zip包
     * 返回null表示压缩失败,
     * 返回ZipFile对象表示压缩成功。
     *
     * @param productZipDir    生成的zip包存放路径 (d:\\xxx\\xx\\)
     * @param productZipName   生成的zip包名 (xxx.zip)
     * @param originalDestPath 要压缩的原始目录地址(e:\\xxx\\xx\\)
     * @throws ZipException
     */
    public static ZipFile fastZip(String productZipDir, String productZipName, String originalDestPath) throws ZipException {

        if (StringUtils.isEmpty(productZipDir)) {
            return null;
        }
        if (StringUtils.isEmpty(productZipName)) {
            return null;
        }
        if (StringUtils.isEmpty(originalDestPath)) {
            return null;
        }

        //zip包存放路径 不存在则建立
        File productDir = new File(productZipDir);
        if (!productDir.exists()) {
            productDir.mkdirs();
        }

        //要压缩的原始目录地址 不存在则返回null
        File originalPath = new File(originalDestPath);
        if (!originalPath.isDirectory()) {
            return null;
        }
        if (!originalPath.exists()) {
            return null;
        }


        // 生成的压缩文件
        ZipFile zipFile = new ZipFile(productZipDir + productZipName);


        ZipParameters parameters = new ZipParameters();
        // 压缩方式 8
        parameters.setCompressionMethod(8);
        // 压缩级别 5
        parameters.setCompressionLevel(5);
        // 要打包的文件夹
        File currentFile = new File(originalDestPath);
        File[] fs = currentFile.listFiles();
        // 遍历originalDestPath文件夹下所有的文件、文件夹
        for (File f : fs) {
            if (f.isDirectory()) {
                zipFile.addFolder(new File(f.getPath()), parameters);
            } else {
                zipFile.addFile(f, parameters);
            }
        }
        //返回zip包对象
        return zipFile;
    }

    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径只有单个文件
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除文件" + fileName + "成功!");
                return true;
            } else {
                System.out.println("删除文件" + fileName + "失败!");
                return false;
            }
        } else {
            System.out.println(fileName + "不存在!");
            return false;
        }
    }


    public static boolean deleteAllFile(String dir) {
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在,或者不是一个目录,则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            System.out.println("删除文件夹失败:" + dir + "不存在!");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子文件夹
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
            // 删除子文件夹
            else if (files[i].isDirectory()) {
                flag = deleteAllFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            System.out.println("删除文件夹失败!");
            return false;
        }
        // 删除当前文件夹
        if (dirFile.delete()) {
            System.out.println("删除文件夹" + dir + "成功!");
            return true;
        } else {
            return false;
        }
    }

    public static String getPath() {
        String env = ProfileUtil.getActiveProfile();
        String path = null;
        if (env.equals("dev")) {
            path = "开发环境地址";
        } else {
            path = "运营环境地址";
        }
        return path;
    }
}

    

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值