Java生成压缩文件(zip、rar 格式)
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 格式)的更多相关文章
- java生成压缩文件
在工作过程中,需要将一个文件夹生成压缩文件,然后提供给用户下载.所以自己写了一个压缩文件的工具类.该工具类支持单个文件和文件夹压缩.放代码: import java.io.BufferedOutput ...
- ASP.NET生成压缩文件(rar打包)
首先引用ICSharpCode.SharpZipLib.dll,没有在这里下载:http://files.cnblogs.com/files/cang12138/ICSharpCode.SharpZi ...
- java上传图片到数据库,涉及压缩文件zip/rar上传等
项目中有这个需求: 1)上传文件通过公司平台的校验,校验成功后,通过接口,返回文件流: 2)我们根据这个文件流进行操作.这里,先将文件流复制文件到项目临时目录WEB-INF/temp;文件使用完毕,删 ...
- java批量解压文件夹下的所有压缩文件(.rar、.zip、.gz、.tar.gz)
// java批量解压文件夹下的所有压缩文件(.rar..zip..gz..tar.gz) 新建工具类: package com.mobile.utils; import com.github.jun ...
- POI以SAX方式解析Excel2007大文件(包含空单元格的处理) Java生成CSV文件实例详解
http://blog.csdn.net/l081307114/article/details/46009015 http://www.cnblogs.com/dreammyle/p/5458280. ...
- PHP生成压缩文件开发实例
大概需求: 每一个订单都有多个文件附件,在下载的时候希望对当前订单的文件自动打包成一个压缩包下载 细节需求:当前订单号_年月日+时间.zip 例如: 1.生成压缩文件,压缩文件名格式: 2.压缩文件 ...
- java对压缩文件进行加密,winrar和好压 直接输入解密密码来使用
<!-- https://mvnrepository.com/artifact/net.lingala.zip4j/zip4j --> <dependency> <gro ...
- Java生成CSV文件实例详解
本文实例主要讲述了Java生成CSV文件的方法,具体实现步骤如下: 1.新建CSVUtils.java文件: package com.saicfc.pmpf.internal.manage.utils ...
- 【转载】在linux下别用zip 用tar来压缩文件 zip解压后还是utf-8 window10是GBK
3.2 使用 unzip 命令解压缩 zip 文件 将 shiyanlou.zip 解压到当前目录: $ unzip shiyanlou.zip 使用安静模式,将文件解压到指定目录: $ un ...
随机推荐
- java中讲讲PrintStream的用法,举例?
[学习笔记] 1.2 PrintStream的用法 从学java第一天,我们就经常用到System.out.println(),实际上查阅文档可知,System.out就是Sun 编的一个Prin ...
- 【洛谷】P5348 密码解锁
[洛谷]P5348 密码解锁 很显然我们可以推导出这个式子 设\(a(m)\)为\(m\)位置的值 \[ \mu(m) = \sum_{m | d} a(d) \\ a(m) = \sum_{m|d} ...
- (二)springMvc 入门
目录 配置前端控制器 servlet拦截方式 springMvc的配置文件 编写处理器类 配置自定义处理器 配置前端控制器 在 web.xml 配置 DispatcherServlet <!-- ...
- ROS的初步学习--创建一个工作空间和一个程序包
快速开始 创建工作区(workspace) 工作区可以作为一个独立的项目进行编译,存放ROS程序的源文件.编译文件和执行文件.建立工作区的方法如下: mkdir -p ~/catkin_ws/src ...
- 【Trie】Immediate Decodability
[题目链接]: https://loj.ac/problem/10052 [题意]: 就是给一些串,是否存在两个串是相同前缀的. [题解] 模板题,不想解释了. [代码]: #include<c ...
- mysql批量修改数据库表引擎
数据库表之前的引擎是MyISAM,影响事务操作,要改成Innodb引擎 查询表引擎 SELECT CONCAT(table_name,' ', engine) FROM information_sch ...
- HeidiSQL 导入Excel数据
一 前言 原文出处:http://blog.csdn.net/qq_27727681/article/details/53944744 二 效果演示: 2000多条数据,顺利导入成功. 三 实现方法 ...
- 数据库优化SQL
sql优化规则: 1.对于查询,尽量不要使用全表扫描,尽量在where子句以及order by所对应的字段建立索引. 2.应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放 ...
- 【IntelliJ IDEA】添加一个新的tomcat,tomcat启动无法访问欢迎页面,空白页,404
===================================第一部分,添加一个tomcat================================================== ...
- C# Base64 操作类
using System; using System.Text; namespace VWFC.IT.CUP.BLL.Util { /// <summary> /// Base64 too ...