Zip4j开源jar包的简单使用

因为对项目突然要发送压缩加密的邮件附件,所以从网上看了一些资料说Zip4j开源框架比较好使,对中文的支持也比较好,所以从网上找了一个代码案例!自己写了一写,现在贴出来,方便以后想用的时候好找

1、

  1 package com.fenghao.zip;
  2 
  3 import java.io.File;
  4 
  5 import java.util.ArrayList;
  6 import java.util.Collections;
  7 
  8 import net.lingala.zip4j.core.ZipFile;
  9 import net.lingala.zip4j.exception.ZipException;
 10 import net.lingala.zip4j.model.ZipParameters;
 11 import net.lingala.zip4j.util.Zip4jConstants;
 12 
 13 
 14 
 15 /**
 16  * 对文件进行压缩和加密
 17  * 对文件进行解压和解密
 18  * @author fenghao
 19  * 
 20  */
 21 public class CompressUtils {
 22 
 23     /**
 24      * 解压加密的压缩文件
 25      * @param zipfile
 26      * @param dest
 27      * @param passwd
 28      * @throws ZipException
 29      */
 30     public void unZip(File zipfile,String dest,String passwd) throws ZipException{
 31         ZipFile zfile=new ZipFile(zipfile);
 32 //        zfile.setFileNameCharset("GBK");//在GBK系统中需要设置
 33         if(!zfile.isValidZipFile()){
 34             throw new ZipException("压缩文件不合法,可能已经损坏!");
 35         }
 36         File file=new File(dest);
 37         if(file.isDirectory() && !file.exists()){
 38             file.mkdirs();
 39         }
 40         if(zfile.isEncrypted()){
 41             zfile.setPassword(passwd.toCharArray());
 42         }
 43         zfile.extractAll(dest);
 44     }
 45     /**
 46      * 压缩文件且加密
 47      * @param src
 48      * @param dest
 49      * @param is
 50      * @param passwd
 51      */
 52     public void zip(String src,String dest,boolean is,String passwd){
 53         File srcfile=new File(src);
 54         //创建目标文件
 55         String destname = buildDestFileName(srcfile, dest);
 56         ZipParameters par=new ZipParameters();
 57         par.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
 58         par.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
 59         if(passwd!=null){
 60             par.setEncryptFiles(true);
 61             par.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
 62             par.setPassword(passwd.toCharArray());
 63         }
 64         try {
 65             ZipFile zipfile=new ZipFile(destname);
 66             if(srcfile.isDirectory()){
 67                 if(!is){
 68                     File[] listFiles = srcfile.listFiles();
 69                     ArrayList<File> temp=new ArrayList<File>();
 70                     Collections.addAll(temp, listFiles);
 71                     zipfile.addFiles(temp, par);
 72                 }
 73                 zipfile.addFolder(srcfile, par);
 74             }else{
 75                 zipfile.addFile(srcfile, par);
 76             }
 77         } catch (ZipException e) {
 78             e.printStackTrace();
 79         }
 80         
 81         
 82     }
 83     /**
 84      * 目标文件名称
 85      * @param srcfile
 86      * @param dest
 87      * @return
 88      */
 89     public String buildDestFileName(File srcfile,String dest){
 90         if(dest==null){//没有给出目标路径时
 91             if(srcfile.isDirectory()){
 92                 dest=srcfile.getParent()+File.separator+srcfile.getName()+".zip";
 93             }else{
 94                 String filename=srcfile.getName().substring(0,srcfile.getName().lastIndexOf("."));
 95                 dest=srcfile.getParent()+File.separator+filename+".zip";
 96             }
 97         }else{
 98             createPath(dest);//路径的创建
 99             if(dest.endsWith(File.separator)){
100                 String filename="";
101                 if(srcfile.isDirectory()){
102                     filename=srcfile.getName();
103                 }else{
104                     filename=srcfile.getName().substring(0, srcfile.getName().lastIndexOf("."));
105                 }
106                 dest+=filename+".zip";
107             }
108         }
109         return dest;
110     }
111     /**
112      * 路径创建
113      * @param dest
114      */
115     private void createPath(String dest){
116         File destDir=null;
117         if(dest.endsWith(File.separator)){
118             destDir=new File(dest);//给出的是路径时
119         }else{
120             destDir=new File(dest.substring(0,dest.lastIndexOf(File.separator)));
121         }
122         if(!destDir.exists()){
123             destDir.mkdirs();
124         }
125     }
126     
127    @org.junit.Test
128    public void Test(){
129        String src="/home/fenghao/document/书籍类资料/Maven实战 高清扫描完整版.pdf";
130        String dest="/home/fenghao/zip/maven/123.zip";
131        zip(src, dest, true, "123456");
132    }
133 }

2、因为自己创建的时maven项目,所以吧jar包依赖也贴出来!

  <!-- https://mvnrepository.com/artifact/net.lingala.zip4j/zip4j -->
    <!-- 对压缩文件和加密的支持 -->
    <dependency>
        <groupId>net.lingala.zip4j</groupId>
        <artifactId>zip4j</artifactId>
        <version>1.3.2</version>
    </dependency>

private void createPath(String dest){File destDir=null;String separator=File.separator;if(dest.endsWith(separator)){destDir=new File(dest);}else{destDir=new File(dest.substring(0, dest.lastIndexOf("/")));//确认:/ \\ 路径分割符号,第一种验证时空//使用/做路径分割时,
        }if(!destDir.exists()){destDir.mkdirs();}}

在Windows测试环境可行

 

private void createPath(String dest){
        File destDir=null;
        String separator=File.separator;
        if(dest.endsWith(separator)){
            destDir=new File(dest);
        }else{
            destDir=new File(dest.substring(0, dest.lastIndexOf("/")));//确认:/ \\ 路径分割符号,第一种验证时空
            //使用/做路径分割时,
        }
        if(!destDir.exists()){
            destDir.mkdirs();
        }
    }

转载于:https://www.cnblogs.com/nihaofenghao/p/6033231.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/256054.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【pyqt5】——入门级模板(ui文件+ui转py文件+逻辑py文件)(消息提示框)

目录 1、ui文件 2、ui转py文件 3、逻辑py文件 4、实例 1&#xff09;ui文件——demo.ui 2&#xff09;ui转py文件——demo.py 3)逻辑py文件——demoLogic.py 4)运行结果 1、ui文件 这个文件是直接通过pyqt5 designer进行设计的&#xff0c;相关配置可见《配置Qt Design…

PCL中点特征描述子PFH、FPFH和VFH简述和示例

文章目录前言一、点特征直方图1.1 PFH1.1.1 法线估计1.1.2 特征计算1.2 FPFH1.3 VFH二、示例2.1 PFH计算2.2 FPFH2.3 VFH前言 点特征直方图是PCL中非常重要的特征描述子&#xff0c;在点云匹配、分割、重建等任务中起到关键作用&#xff0c;可以对刚体变换、点云密度和噪声均有…

BZOJ 1005: [HNOI2008]明明的烦恼

BZOJ 1005: [HNOI2008]明明的烦恼 Description 自从明明学了树的结构,就对奇怪的树产生了兴趣......给出标号为1到N的点,以及某些点最终的度数,允许在 任意两点间连线,可产生多少棵度数满足要求的树? Input 第一行为N(0 < N < 1000), 接下来N行,第i1行给出第i个节点的度…

Apache Directory 指令

<Directory> 指令 语法&#xff1a;<Directory directory-path> ... </Directory> <Directory>和</Directory>用于封装一组指令&#xff0c;使之仅对某个目录及其子目录生效。任何可以在"directory"作用域中使用的指令都可以使用。Dir…

来一个炫酷的导航条

本文分享一个带动画效果的中英文切换导航条。 鼠标放上去试一下&#xff1a; INDEX 首页 BBS 社区 HOME 我 1.用CSS3实现 效果看上去复杂&#xff0c;其实我们先来做出一个样式&#xff0c;就很简单了。如下&#xff1a; 代码&#xff1a; <nav><ul class"list…

基于C++的opencv中Mat矩阵运算方法总结

文章目录前言一、Mat运算种类1.1 代数运算1.2 类型转换前言 Mat类是目前opencv最为常用的图像数据格式&#xff0c;其优点在于无需手动开辟内存空间和实时释放&#xff0c;针对此类的各种运算方法有很多&#xff0c;本文按照各种运算方法的种类进行简单的总结和示例。 一、Mat…

【pyqt5】——信号与槽

一、简单Demo 简单使用信号和槽&#xff08;之前常用的使用方式&#xff09;&#xff1a; class DemoWin(QMainWindow):def __init__(self):super().__init__()self.initUI()def initUI(self):self.resize(400, 250)self.btn QPushButton("发送信号", self)# 发送…

JSON - 简介

JSON - 简介 JSON实例 <!DOCTYPE html> <html> <head> <meta charset"utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <h2>JavaScript 创建 JSON 对象</h2> <p> 网站名称: <spa…

mysql慢日志管理

一、日志切割 原理&#xff1a; 1、cp一个慢日志备份 2、清空原理的慢日志 3、写成脚本&#xff0c;每天一切&#xff0c;这样就ok啦 二、查找日志中的慢日志 1、做了日志切割&#xff08;慢日志文件就小了&#xff09; 2、查找某个时间的慢日志 日志时间格式&#xff1a; # Ti…

【深度学习】mask_rcnn训练自己的数据集以及模型使用(实践结合GitHub项目)

根据requirements - 开源项目默认的.txt进行库安装 环境&#xff1a;WIN10 Anoconda Pycharm python3.6.2 mask_rcnn基本流程1、训练 1)labelme进行目标物体标记&#xff0c;生成json文件&#xff0c;含点坐标、以及各个物体的标签label; json文件的格式&#xff1a;&…

EXCEL小技巧:如何统计非空单元格

http://club.excelhome.net/thread-1187271-1-1.html 下面教大家如果用函数统计非空单元格的数量 首先我们来介绍几个统计函数&#xff1a; 1.COUNT(value1,value2,...) 统计包含数字的单元格个数 2.COUNTA(value1,value2,...) 统计非空单元格的个数 3.COUNTBLANK(range&…

easyui 页签

昨天开始搭后台框架&#xff0c;到晚上的时候遇到了一个现在觉得挺可笑但是当时一直很纠结很纠结的问题&#xff0c;这个问题刚刚解决出来&#xff0c;把它拿出来说说&#xff0c;让自己长点儿记性&#xff0c;希望大家不要犯我这个错误啊 在backstage.jsp页面中我写了一个方法…

未在本地计算机上注册“Microsoft.Jet.OLEDB.4.0”提供程序。

报错信息&#xff1a; 解决方案&#xff1a; 1、“设置应用程序池默认属性”/“常规”/”启用32位应用程序”&#xff0c;设置为 true。 如下图所示&#xff1a;&#xff08;已测试&#xff0c;好使&#xff09; 方法二&#xff1a;生成->配置管理器->平台->点击Any C…

UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figur

“UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure”在利用mask_rcnn进行物体检测的时候出现的问题&#xff0c;主要是因为matplotlib的使用格式不对 可以检查者两个地方&#xff1a; 1、visualize.py中 import mat…

008. 限制上传文件的大小

第一种方法: 利用web.config的配置文件项, 进行设置; 前端aspx示例: <% Page Language"C#" AutoEventWireup"true" CodeFile"sendOutEmail.aspx.cs" Inherits"sendOutEmail" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHT…

查询实例及其代码

一、 设有一数据库&#xff0c;包括四个表&#xff1a;学生表&#xff08;Student&#xff09;、课程表&#xff08;Course&#xff09;、成绩表&#xff08;Score&#xff09;以及教师信息表&#xff08;Teacher&#xff09;。四个表的结构分别如表1-1的表&#xf…

pyinstaller打包执行exe出现“ModuleNotFoundError: No module named ‘scipy.spatial.transform._rotation_group”

这个是因为打包后的第三方库中缺少了pyd文件 具体的解决方法&#xff1a; 去环境下找到相应的py文件&#xff0c;根据https://blog.csdn.net/qq_41007606/article/details/109565069文章写的方法&#xff0c;将py编译成pyd文件&#xff0c;然后将pyd文件复制到dist相应的第三…

浙江中医药大学第十一届程序设计竞赛题解

官方题解&#xff1a;http://www.jnxxhzz.com/Article/article/9.html 2019: 特产 Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 548 Solved: 154[Submit][Status][Web Board]Description Input Output 输出一个整数表示dd带回来的特产重量 Sample Input 2 3 6 1 3Sample …

vijos p1002——过河(noip2005提高组T2)

描述 在河上有一座独木桥&#xff0c;一只青蛙想沿着独木桥从河的一侧跳到另一侧。在桥上有一些石子&#xff0c;青蛙很讨厌踩在这些石子上。由于桥的长度和青蛙一次跳过的距离都是正整数&#xff0c;我们可以把独木桥上青蛙可能到达的点看成数轴上的一串整点&#xff1a;0&…

JNI学习

1. 目前调用关系已经搞清楚&#xff0c;需要编译一个so或者dll的动态库给java调用。 2. env有很多方法现在还不清楚&#xff0c; 获得属性句柄。 JNI方法描述符&#xff0c;主要就是在括号里放置参数&#xff0c;在括号后面放置返回类型&#xff0c;如下&#xff1a;&#xff0…