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 ...
随机推荐
- select示例
#include <sys/select.h> #include <sys/time.h> #include <sys/types.h> #include < ...
- Linux安装zookeeper集群
一.单机部署: ①下载.解压 http://archive.apache.org/dist/zookeeper/ tar -zxf zookeeper-3.4.10.tar.gz -C /usr/lo ...
- HTTP请求方法:GET、HEAD、POST、PUT、DELETE、CONNECT、OPTIONS、TRACE 说明
平时的Rest开发,用到的都是GET,POST,PUT,DELETE类型的请求. 但Rest支持的请求类型不止前面4种,还有其他几种. 下面部分转自: https://www.html.cn/arch ...
- 【模板】C++高精度加法
所谓高精度加法就是对两个和可能会超过long long数据范围的数进行加法运算.这种情况下,显然不能使用常规的方法进行运算. 那么,不妨考虑一下人在纸上是如何进行加法运算的.当人进行加法运算时,通常会 ...
- Maven学习存档(3)——eclipse集成maven
一.安装Maven插件 在eclipse的菜单中选择Help——Install New Software 在弹出框的Work with中写入插件安装地址:http://m2eclipse.sonaty ...
- DVWA漏洞演练平台 - 文件上传
DVWA(Damn Vulnerable Web Application)是一个用来进行安全脆弱性鉴定的PHP/MySQL Web应用,旨在为安全专业人员测试自己的专业技能和工具提供合法的环境,帮助w ...
- VS 之github
VS 代码发布到TFS上 1. 登录 visualstudio.com. 进入 https://qgb.visualstudio.com Create Project 这里是相当于新建了一个文件夹 ...
- Oracle 以及 PLSQL安装
今天重装系统遇到oracle 安装的问题咯 ,oracle安装过程中很多疑难杂症咯 1如果之前装过,记得去删除注册表的Oracle 相关的文件 ,请百度有很多教程咯 2这个必须要勾选的!因为的是11g ...
- bootstrap-table的简单使用
先上效果图: 第一步:引用bootstrap-table的样式和js. @Styles.Render("~/assets/css/bootstrap.css") @Styles.R ...
- PHP转码函数mb_convert_encoding() 和iconv()
注意:函数mb_convert_encoding的执行效率比iconv差,且需开启php的mbstring扩展. 一般情况下使用iconv,但此函数在碰到无法转码字符会丢弃,此种情况下可以用mb_co ...