Java实现多文件压缩加密并重命名压缩文件对象的方法

2022-07-25,,,,

java 多文件加密压缩 添加文件加密压缩工具包依赖

<!-- zip4j压缩工具 -->
  <dependency>
   <groupid>net.lingala.zip4j</groupid>
   <artifactid>zip4j</artifactid>
   <version>1.3.2</version>
  </dependency>

话不多说,直接上干货

完整代码如下:

package com.rhtcms.cms.api.admin.main;
import org.json.jsonobject;
import org.springframework.stereotype.controller;
import net.lingala.zip4j.core.zipfile;
import net.lingala.zip4j.exception.zipexception;
import net.lingala.zip4j.model.zipparameters;
import net.lingala.zip4j.util.zip4jconstants;
import java.io.*;
import java.util.*;

public class filecompressionapiact {
 /**
  * 复制压缩文件路径 ps:此路径必须为空文件夹,在压缩完成后此文件夹将被清空目录
  */
 private static string copypath = "c:/users/administrator/desktop/压缩测试/压缩测试作业复制";

 private static long time = system.currenttimemillis();//以时间戳作为文件名,防止重命名问题

 /**
  * 压缩包路径: 路径+压缩包名称 eg: c:/users/administrator/desktop/压缩测试/ + test.zip
  */
 private static string zippath = "c:/users/administrator/desktop/压缩测试/" + time + ".zip";

 /**
  * 可支持的压缩文件格式
  */
 private static string[] filetype = {"doc", "docx", "pdf", "txt"};

 /**
  * @param filepath 压缩文件路径
  * @param filerename 压缩文件重命名名称
  * @param password 加密密码
  * @return
  * @title: zipfilesandencrypt
  * @description: 将指定路径下的文件压缩至指定zip文件,并以指定密码加密,若密码为空,则不进行加密保护
  * @author: 张庆裕
  * @date: 2021/01/04
  */
 //@requestmapping("/filecompression/list")
 public string zipfilesandencrypt(list<file> filepath, list<string> filerename, string password) {
  /**
   * 压缩成功的文件数量
   */
  int successcount = 0;
  /**
   * 压缩失败的文件数量
   */
  int failcount = 0;
  /**
   * 返回数据
   */
  jsonobject ob = new jsonobject();

  arraylist<string> failfile = new arraylist<>();//压缩失败的文件路径

  arraylist<string> failfilepath = new arraylist<>();//路径错误的文件

  arraylist<file> filestoadd = new arraylist<>();//压缩路径的集合

  //创建复制文件夹
  file folder = new file(copypath);
  if(!folder.exists()){//如果文件夹不存在
   boolean mkdir = folder.mkdir();//创建文件夹
   if(!mkdir){//系统未找到该路径
    throw new runtimeexception("复制文件路径出错,请修改复制文件夹路径");
   }
  }else{//文件夹存在
   file[] listfiles = folder.listfiles();
   if(listfiles.length > 0){//如何文件夹下存在目录则,停止压缩,防止删除其他文件
    throw new runtimeexception("复制的文件夹不为空,请选择空文件夹!");
   }
  }

  for (int i = 0; i < filepath.size(); i++) {//遍历压缩文件数据
   file file = filepath.get(i);//获取原文件
   if (!file.exists()) {//防止文件异常,首先再次确认文件路径是否存在
    // 文件不存在
    failcount++;
    failfilepath.add(file.getpath());
    system.out.println("文件:" + file.getpath() + " 路径不存在!");
    ob.put("failfilepath", failfilepath);
   } else {//文件存在
    //获取原文件路径
    string path = filepath.get(i).getpath();
    //获取最后一个点的位置
    int lastindexof = path.lastindexof(".");
    //获取文件后缀 eg: txt , doc , pdf ....
    string suffix = path.substring(lastindexof + 1);
    if (arrays.aslist(filetype).contains(suffix)) {  //判断文件格式是否合格,合格添加至压缩文件中
     //获取原文件名称
     file oldname = new file(file.getpath());

     //先复制文件
     file newname = new file(copypath + "/" + file.getname());
     try {
      copyfile(oldname, newname);
     } catch (exception e) {
      e.printstacktrace();
     }
     //string path = newname.getpath();//获取复制文件的路径
     string parentpath = newname.getparent();//获取复制出来的文件的父级目录
     string rename = filerename.get(i);//获取重命名的名称

     newname.renameto(new file(parentpath + "/" + rename));//重命名复制出来的文件
     filestoadd.add(new file(parentpath + "/" + rename));//将赋值出来的文件添加到压缩文件集合中
     successcount++;//压缩成功文件数量+1
    } else {
     failfile.add(file.getpath());
     failcount++;//压缩失败文件数量+1

     ob.put("filepath", failfile);
     system.out.println("该文件压缩失败:" + file.getpath() + " 文件格式错误!");
    }
   }
  }
  //压缩配置
  try {
   zipparameters parameters = new zipparameters();
   parameters.setcompressionmethod(zip4jconstants.comp_deflate);//压缩方式
   //设置压缩级别
   //deflate_level_fastest - 最低压缩级别,但压缩速度更高
   //deflate_level_fast - 低压缩级别,但压缩速度更高
   //deflate_level_normal - 压缩水平速度之间的最佳平衡
   //deflate_level_maximum - 高压缩级别,但速度不佳
   //deflate_level_ultra - 最高压缩级别但速度较低
   parameters.setcompressionlevel(zip4jconstants.deflate_level_normal);//压缩级别
   if (password != null && password!="") {
    parameters.setencryptfiles(true);//设置压缩文件加密
    parameters.setencryptionmethod(zip4jconstants.enc_method_standard);//加密方式
    parameters.setpassword(password);//设置加密密码
   }
   zipfile zipfile = new zipfile(zippath);//创建压缩路径
   zipfile.setfilenamecharset("gbk");//设置压缩编码
   zipfile.addfiles(filestoadd, parameters);//添加压缩文件并进行加密压缩
   //压缩完成后清空复制的文件目录
   deletedir(copypath);
   ob.put("zippath", zippath);
   ob.put("successcount", successcount);
   ob.put("failcount", failcount);
  } catch (zipexception e) {
   //清空复制的文件目录
   deletedir(copypath);
   ob.put("unknown", "未知异常,压缩失败!");
   system.out.println("文件压缩出错");
   e.printstacktrace();
  }
  return ob.tostring();
 }

 /**
  * @description: 文件复制
  * @param: resource 原文件路径
  * @param: target 新文件路径
  * @return:
  * @author: 张庆裕
  * @date: 2021/1/6
  */
 public void copyfile(file resource, file target) throws exception {
  // 输入流 --> 从一个目标读取数据
  // 输出流 --> 向一个目标写入数据
  long start = system.currenttimemillis();
  // 文件输入流并进行缓冲
  fileinputstream inputstream = new fileinputstream(resource);
  bufferedinputstream bufferedinputstream = new bufferedinputstream(inputstream);
  // 文件输出流并进行缓冲
  fileoutputstream outputstream = new fileoutputstream(target);
  bufferedoutputstream bufferedoutputstream = new bufferedoutputstream(outputstream);
  // 缓冲数组
  // 大文件 可将 1024 * 2 改大一些,但是 并不是越大就越快
  byte[] bytes = new byte[1024 * 2];
  int len = 0;
  while ((len = inputstream.read(bytes)) != -1) {
   bufferedoutputstream.write(bytes, 0, len);
  }
  // 刷新输出缓冲流
  bufferedoutputstream.flush();
  //关闭流
  bufferedinputstream.close();
  bufferedoutputstream.close();
  inputstream.close();
  outputstream.close();
  long end = system.currenttimemillis();
  system.out.println("复制文件:" + resource.getpath() + " 成功 耗时:" + (end - start) / 1000 + " s");
 }

 /**
  * @description: 清空复制压缩文件下的内容
  * @param: path 复制文件夹的路径
  * @return:
  * @author: 张庆裕
  * @date: 2021/1/6
  */
 public boolean deletedir(string path) {
  file file = new file(path);
  if (!file.exists()) {//判断是否待删除目录是否存在
   system.err.println("the dir are not exists!");
   return false;
  }
  string[] content = file.list();//取得当前目录下所有文件和文件夹
  for (string name : content) {
   file temp = new file(path, name);
   if (temp.isdirectory()) {//判断是否是目录
    deletedir(temp.getabsolutepath());//递归调用,删除目录里的内容
    temp.delete();//删除空目录
   } else {
    if (!temp.delete()) {//直接删除文件
     system.err.println("failed to delete " + name);
    }
   }
  }
  return true;
 }

 /**
  * @description: 文件压缩测试接口
  * @param:
  * @return:
  * @author: 张庆裕
  * @date: 2021/1/7
  */
 public static void main(string[] args) {
  list<file> filepath = new arraylist<>();//压缩文件路径
  filepath.add(new file("c:/users/administrator/desktop/压缩测试/yasuo/oa平台问题.docx"));
  filepath.add(new file("c:/users/administrator/desktop/压缩测试/yasuo/oa平台问题1.docx"));
  filepath.add(new file("c:/users/administrator/desktop/压缩测试/yasuo/oa平台问题2.docx"));
  filepath.add(new file("c:/users/administrator/desktop/压缩测试/yasuo/oa平台问题3.docx"));
  filepath.add(new file("c:/users/administrator/desktop/压缩测试/yasuo/邮箱1.md"));
  filepath.add(new file("c:/users/administrator/desktop/压缩测试/yasuo/邮箱2.md"));

  list<string> filerename = new arraylist<>();//压缩文件重命名名称
  filerename.add("oa平台问题.docx");
  filerename.add("oa平台问题1.docx");
  filerename.add("oa平台问题2.docx");
  filerename.add("oa平台问题3.docx");
  filerename.add("邮箱副本1.md");
  filerename.add("邮箱副本2.md");

  string password = "123456";//加密密码
  //请在单元测试进行测试, 或者将方法改为 static 方法
  //string result = zipfilesandencrypt(filepath, filerename, password);
  //system.out.println(result);
 }

}

效果如下:

到此这篇关于java实现多文件压缩加密并重命名压缩文件对象的方法的文章就介绍到这了,更多相关java多文件压缩加密内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Java实现多文件压缩加密并重命名压缩文件对象的方法.doc》

下载本文的Word格式文档,以方便收藏与打印。