jar坐标:

        <dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.10.5</version>
</dependency>

话不多说,直接上代码

package com.demo.student.util;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream; import java.io.*; /**
* 生成压缩文件 (zip,rar 格式)
*/
public class CompressUtil { /**
* @param path 要压缩的文件路径
* @param format 生成的格式(zip、rar)d
*/
public static void generateFile(String path, String format) throws Exception { File file = new File(path);
// 压缩文件的路径不存在
if (!file.exists()) {
throw new Exception("路径 " + path + " 不存在文件,无法进行压缩...");
}
// 用于存放压缩文件的文件夹
String generateFile = file.getParent() + File.separator +"CompressFile";
File compress = new File(generateFile);
// 如果文件夹不存在,进行创建
if( !compress.exists() ){
compress.mkdirs();
} // 目的压缩文件
String generateFileName = compress.getAbsolutePath() + File.separator + "AAA" + file.getName() + "." + format; // 输入流 表示从一个源读取数据
// 输出流 表示向一个目标写入数据 // 输出流
FileOutputStream outputStream = new FileOutputStream(generateFileName); // 压缩输出流
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream)); generateFile(zipOutputStream,file,""); System.out.println("源文件位置:" + file.getAbsolutePath() + ",目的压缩文件生成位置:" + generateFileName);
// 关闭 输出流
zipOutputStream.close();
} /**
* @param out 输出流
* @param file 目标文件
* @param dir 文件夹
* @throws Exception
*/
private static void generateFile(ZipOutputStream out, File file, String dir) throws Exception { // 当前的是文件夹,则进行一步处理
if (file.isDirectory()) {
//得到文件列表信息
File[] files = file.listFiles(); //将文件夹添加到下一级打包目录
out.putNextEntry(new ZipEntry(dir + "/")); dir = dir.length() == 0 ? "" : dir + "/"; //循环将文件夹中的文件打包
for (int i = 0; i < files.length; i++) {
generateFile(out, files[i], dir + files[i].getName());
} } else { // 当前是文件 // 输入流
FileInputStream inputStream = new FileInputStream(file);
// 标记要打包的条目
out.putNextEntry(new ZipEntry(dir));
// 进行写操作
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) > 0) {
out.write(bytes, 0, len);
}
// 关闭输入流
inputStream.close();
} }   // 测试
public static void main(String[] args) {
String path = "";
String format = "rar"; try {
generateFile(path, format);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
} } }

结果图:

压缩整个文件

    /**
* 递归压缩文件
* @param output ZipOutputStream 对象流
* @param file 压缩的目标文件流
* @param childPath 条目目录
*/
private static void zip(ZipOutputStream output,File file,String childPath){
FileInputStream input = null;
try {
// 文件为目录
if (file.isDirectory()) {
// 得到当前目录里面的文件列表
File list[] = file.listFiles();
childPath = childPath + (childPath.length() == 0 ? "" : "/")
+ file.getName();
// 循环递归压缩每个文件
for (File f : list) {
zip(output, f, childPath);
}
} else {
// 压缩文件
childPath = (childPath.length() == 0 ? "" : childPath + "/")
+ file.getName();
output.putNextEntry(new ZipEntry(childPath));
input = new FileInputStream(file);
int readLen = 0;
byte[] buffer = new byte[1024 * 8];
while ((readLen = input.read(buffer, 0, 1024 * 8)) != -1) {
output.write(buffer, 0, readLen);
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
// 关闭流
if (input != null) {
try {
input.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
} } /**
* 压缩文件(文件夹)
* @param path 目标文件流
* @param format zip 格式 | rar 格式
* @throws Exception
*/
public static String zipFile(File path,String format) throws Exception {
String generatePath = "";
if( path.isDirectory() ){
generatePath = path.getParent().endsWith("/") == false ? path.getParent() + File.separator + path.getName() + "." + format: path.getParent() + path.getName() + "." + format;
}else {
generatePath = path.getParent().endsWith("/") == false ? path.getParent() + File.separator : path.getParent();
generatePath += path.getName().substring(0,path.getName().lastIndexOf(".")) + "." + format;
}
// 输出流
FileOutputStream outputStream = new FileOutputStream( generatePath );
// 压缩输出流
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(outputStream));
zip(out, path,"");
out.flush();
out.close(); return generatePath;

使用

    // 使用例子
public static void main(String[] args) { String path = "F:/test";
String format = "zip";
try {
System.out.println(zipFile(new File(path),format));
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
} }

解压

    /**
*
* @param sourceZip 待解压文件路径
* @param destDir 解压到的路径
*/
public static String unZip(String sourceZip, String destDir) {
//保证文件夹路径最后是"/"或者"\"
if( !destDir.endsWith("/") ){
destDir += File.separator;
}
String newDir = "";
File sourceFile = new File(sourceZip);
newDir = sourceFile.getName().substring(0,sourceFile.getName().lastIndexOf("."));
File destDirFile = new File(destDir + newDir); Project p = new Project();
Expand e = new Expand();
e.setProject(p);
e.setSrc(sourceFile);
e.setOverwrite(true);
e.setDest(destDirFile);
/*
ant下的zip工具默认压缩编码为UTF-8编码,
而winRAR软件压缩是用的windows默认的GBK或者GB2312编码
所以解压缩时要制定编码格式
*/
e.setEncoding("gbk");
e.execute();
return destDirFile.getAbsolutePath();
}

Java生成压缩文件(zip、rar 格式)的更多相关文章

  1. java生成压缩文件

    在工作过程中,需要将一个文件夹生成压缩文件,然后提供给用户下载.所以自己写了一个压缩文件的工具类.该工具类支持单个文件和文件夹压缩.放代码: import java.io.BufferedOutput ...

  2. ASP.NET生成压缩文件(rar打包)

    首先引用ICSharpCode.SharpZipLib.dll,没有在这里下载:http://files.cnblogs.com/files/cang12138/ICSharpCode.SharpZi ...

  3. java上传图片到数据库,涉及压缩文件zip/rar上传等

    项目中有这个需求: 1)上传文件通过公司平台的校验,校验成功后,通过接口,返回文件流: 2)我们根据这个文件流进行操作.这里,先将文件流复制文件到项目临时目录WEB-INF/temp;文件使用完毕,删 ...

  4. java批量解压文件夹下的所有压缩文件(.rar、.zip、.gz、.tar.gz)

    // java批量解压文件夹下的所有压缩文件(.rar..zip..gz..tar.gz) 新建工具类: package com.mobile.utils; import com.github.jun ...

  5. POI以SAX方式解析Excel2007大文件(包含空单元格的处理) Java生成CSV文件实例详解

    http://blog.csdn.net/l081307114/article/details/46009015 http://www.cnblogs.com/dreammyle/p/5458280. ...

  6. PHP生成压缩文件开发实例

    大概需求: 每一个订单都有多个文件附件,在下载的时候希望对当前订单的文件自动打包成一个压缩包下载 细节需求:当前订单号_年月日+时间.zip  例如: 1.生成压缩文件,压缩文件名格式: 2.压缩文件 ...

  7. java对压缩文件进行加密,winrar和好压 直接输入解密密码来使用

    <!-- https://mvnrepository.com/artifact/net.lingala.zip4j/zip4j --> <dependency> <gro ...

  8. Java生成CSV文件实例详解

    本文实例主要讲述了Java生成CSV文件的方法,具体实现步骤如下: 1.新建CSVUtils.java文件: package com.saicfc.pmpf.internal.manage.utils ...

  9. 【转载】在linux下别用zip 用tar来压缩文件 zip解压后还是utf-8 window10是GBK

    3.2 使用 unzip 命令解压缩 zip 文件 将 shiyanlou.zip 解压到当前目录:   $ unzip shiyanlou.zip 使用安静模式,将文件解压到指定目录:   $ un ...

随机推荐

  1. Qt中mouseMoveEvent无效

    最近用Qt软件界面,需要用到mouseMoveEvent,研究了下,发现些问题,分享一下. 在Qt中要捕捉鼠标移动事件需要重写MouseMoveEvent,但是MouseMoveEvent为了不太耗资 ...

  2. poj1797(dijstra变形,求最小边的最大值)

    题目链接:https://vjudge.net/problem/POJ-1797 题意:n个点,m条带权边,求点1到点n的所有路径中最小边的最大值. 思路: 和poj2253一样,只不过那题n< ...

  3. HTML5 & CSS初学者教程(详细、通俗易懂)

    前端语言基础:HTML5 & CSS (一) HTML5:超文本标记语言 (1) 基本概念 是由一系列成对出现的元素标签(标记)嵌套组合而成 ( XML也是标签构成的 ) 这些标签以的形式出现 ...

  4. Mac查看端口号是否被占用及释放

    1.查看使用端口进程 lsof -i: 端口号 2.释放进程 kill 你的PID 3.再次执行第一步,是否无进程占用 lsof -i: 端口号

  5. LeetCode 第 14 场双周赛

    基础的 api 还是不够熟悉啊 5112. 十六进制魔术数字 class Solution { public: char *lltoa(long long num, char *str, int ra ...

  6. pt-online-schema-change使用

    MySQL ddl 的问题现状 在 运维mysql数据库时,我们总会对数据表进行ddl 变更,修改添加字段或者索引,对于mysql 而已,ddl 显然是一个令所有MySQL dba 诟病的一个功能,因 ...

  7. Algorithm negotiation failed

    #用pycharm工具ssh client 报 algorithm negotiation failed#导致原因:是ssh升级后,为了安全,默认不再采用原来一些加密算法,我们手工添加进去即可#目前出 ...

  8. k8s之RBAC-基于角色的访问控制

    一个在名称空间内的对象的完整url模板: Object_URL: /apis/<GROUP>/<VERSION>/namespaces/<NAMESPACE_NAME&g ...

  9. C语言快速判断素数——不超时

    这属于算法上的问题,好好考虑一下算法,还要考虑一下素数的定义. 素数是只有1和本身能整除的整数.所以在求素数的时候,要将素数与1到素数本身中间的所有整数都相除,看是否有整除的数,如果有,那肯定不是素数 ...

  10. STM32 USB Virtual COM

    STM32 USB Virtual COM USB转串口的功能实现   这次讲的是如何实现USB转串口功能的实现.首先看看工程的布局吧: 我们主要要介绍的文件的在USB_User这个组文件.从上面的截 ...