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. Information retrieval (IR class1)

    1. 什么是IR? IR与数据库的区别? 答:数据库是检索结构化的数据,例如关系数据库:而信息检索是检索非结构化/半结构化的数据,例如:一系列的文本.信息检索是属于NLP(自然语言处理)里面最实用的一 ...

  2. 在文件每行后边添加固定文本(shell)

    例子: 对/code/shell/servers 中每一行最后添加用户名和密码   原来长这样: /code/shell/servers 我对其每行添加" root 950102DK&quo ...

  3. RHCE\RHCSA

    加油,老杨,所有的事情坚持到最后都是最好的,之所以现在觉得不好,是因为还没有坚持到最后,终于考过了,哈哈哈,下一个目标OCP

  4. 【AtCoder】ARC061

    ARC061 C - たくさんの数式 / Many Formulas 这个其实\(10^5\)也能做.. 就是\(dp[i]\)表示到第i位的方案数,\(sum[i]\)表示延伸到第i位之前的所有方案 ...

  5. LC 387. First Unique Character in a String

    题目描述 Given a string, find the first non-repeating character in it and return it's index. If it doesn ...

  6. 20190716-Python网络数据采集/第 2 章 复杂HTML解析

    # P29/9# 解析,要考虑到可持续性问题,对方反爬修改后,仍继续有效,方为优秀代码# 解析一个目标网页前,需要做到以下几点:(1)明确目标内容:(2)寻找“打印此页”的链接,或查看网站有无HTML ...

  7. centos官网上对应的版本

    7.4版本的链接,版本可以返回前级目录跟换,下面是各个版本的区别: 1.CentOS-7-DVD版本:DVD是标准安装盘,一般下载这个就可以了. 2.CentOS-7-NetInstall版本:网络安 ...

  8. @media screen媒体查询实现页面自适应布局

    @media screen and (min-width:1200px){ //大于等于1200px才会进入 }   @media screen and (max-width:375px) { //小 ...

  9. Innosetup设置控制面版中的名称显示和图标

    //设置控制面板中程序图标UninstallDisplayIcon={app}\logo.ico //设置控制面板中程序的名称Uninstallable=yesUninstallDisplayName ...

  10. sql临时表 通过临时表循环处理数据

    -- 创建临时表 IF OBJECT_ID('tempdb.dbo.#temprecord','U') IS NOT NULL DROP TABLE dbo.#temprecord; GO SELEC ...