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 ...
随机推荐
- brew update慢,brew install慢如何解决?
主要是资源访问太慢造成的,替换默认源镜像就行. brew使用国内镜像源 这里用中科大的,另外还有清华的可用 1 2 3 4 5 6 7 8 9 10 # 步骤一 cd "$(brew ...
- thinkphp中return $this->fetch的问题
当reture放在foreach循环外面,也就是现在的位置的时候,会报错.如下图.但当return放在foreach语句里面的时候就不会报错,但因为return会结束语句,这也就导致了foreach只 ...
- javaweb项目的全局监听配置
在项目中有时候会遇到全局监听的需求,而全局性的监听该如何配置,代码如下: package com.demo.listener; import javax.servlet.ServletContextE ...
- c# 金钱大写转小写工具类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- 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 ...
- git 使用2
安装 1.下载对应版本:https://git-scm.com/download 2.安装git:在选取安装路径的下一步选取 Use a TrueType font in all console wi ...
- 火狐 , IE , 谷歌浏览器的 驱动下载地址汇总
一.Firefox和驱动下载地址 所有火狐浏览器版本下载地址:http://ftp.mozilla.org/pub/firefox/releases/ 所有火狐驱动geckodriver版本下载地址: ...
- 简单分析synchronized不会锁泄漏的原因
最近看到一句话:内部锁synchronized不会造成锁泄漏(Lock Leak). 锁泄漏是指一个线程获得某个锁以后,由于程序的错误.缺陷致使该锁一直没法被释放而导致其他线程一直无法获得该锁的现象. ...
- 利用Mathpix Snipping Tool轻松在markdown/LaTeX中输入电子书和论文的数学公式
最近写图形学博客写累了,公式太多了,一个个输入实在太累,所以从数学建模队友那里吃了一个安利. 官网下载 下载安装后,直接新建一个截图,就可以转成LaTeX数学公式了.效果如下: 爽的一批啊!!! 另外 ...
- uni-app使用Canvas绘图
最近公司项目在用uni-app做小程序商城,其中商品和个人需要生成图片海报,经过摸索记录后将一些重点记录下来.这里有两种方式来生成 1.后台控制生成 2.前端用canvas合成图片 这里我们只讲使用c ...