java实现单个或多个文件的压缩、解压缩 支持zip、rar等格式
代码如下:
package com.cn.util; import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand; /**
* 压缩文件工具类
* @author sun.kai
* 2016年8月14日
*/
public class ZipUtil {
static final int BUFFER = 8192; private static File zipFile; /**
* 压缩单个或多文件方法
* @param zipPath 压缩后的文件路径
* @param srcPathName 要压缩的文件路径
* 参数srcPathName也可以定义成数组形式,需调用方把参数封装到数组中传过来即可
*/
public static void compress(String zipPath,String... srcPathName) {
//压缩后的文件对象
zipFile = new File(zipPath);
try {
//创建写出流操作
FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,new CRC32());
ZipOutputStream out = new ZipOutputStream(cos);
for(String srcPath:srcPathName){
//创建需要压缩的文件对象
File file = new File(srcPath);
if (!file.exists()){
throw new RuntimeException(srcPath + "不存在!");
}
/*
* (1)如果在zip压缩文件中不需要一级文件目录,定义String basedir = "";
* 下面的compress方法中当判断文件file是目录后不需要加上basedir = basedir + file.getName() + File.separator;
* (2)如果只是想在压缩后的zip文件里包含一级文件目录,不包含二级以下目录,
* 直接在这定义String basedir = file.getName() + File.separator;
* 下面的compress方法中当判断文件file是目录后不需要加上basedir = basedir + file.getName() + File.separator;
* (3)如果想压缩后的zip文件里包含一级文件目录,也包含二级以下目录,即zip文件里的目录结构和原文件一样
* 在此定义String basedir = "";
* 下面的compress方法中当判断文件file是目录后需要加上basedir = basedir + file.getName() + File.separator;
*/
//String basedir = file.getName() + File.separator;
String basedir = "";
compress(file, out, basedir);
}
out.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void compress(File file, ZipOutputStream out, String basedir) {
/*
* 判断是目录还是文件
*/
if (file.isDirectory()) {
basedir += file.getName() + File.separator;
compressDirectory(file, out, basedir);
} else {
System.out.println("压缩:" + basedir + file.getName());
compressFile(file, out, basedir);
}
} /**
* 压缩一个目录
*/
private static void compressDirectory(File dir, ZipOutputStream out, String basedir) {
if (!dir.exists()){
return;
}
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
/* 递归 */
compress(files[i], out, basedir);
}
} /**
* 压缩一个文件
*/
private static void compressFile(File file, ZipOutputStream out, String basedir) {
if (!file.exists()) {
return;
}
try {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
//创建Zip实体,并添加进压缩包
ZipEntry entry = new ZipEntry(basedir + file.getName());
out.putNextEntry(entry);
//读取待压缩的文件并写进压缩包里
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
bis.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
} /**
* 解压缩
* @param sourceFile 要解压缩的文件的路径
* @param destDir 解压缩后的目录路径
* @throws Exception
*/
public static void deCompress(String sourceFile,String destDir) throws Exception{
//创建需要解压缩的文件对象
File file = new File(sourceFile);
if (!file.exists()){
throw new RuntimeException(sourceFile + "不存在!");
}
//创建解压缩的文件目录对象
File destDiretory = new File(destDir);
if(!destDiretory.exists()){
destDiretory.mkdirs();
}
/*
* 保证文件夹路径最后是"/"或者"\"
* charAt()返回指定索引位置的char值
*/
char lastChar = destDir.charAt(destDir.length()-1);
if(lastChar!='/'&&lastChar!='\\'){
//在最后加上分隔符
destDir += File.separator;
}
unzip(sourceFile, destDir);
} /**
* 解压方法
* 需要ant.jar
*/
private static void unzip(String sourceZip,String destDir) throws Exception{
try{
Project p = new Project();
Expand e = new Expand();
e.setProject(p);
e.setSrc(new File(sourceZip));
e.setOverwrite(false);
e.setDest(new File(destDir));
e.execute();
}catch(Exception e){
throw e;
}
} }
测试代码:
package com.test.test;
import com.cn.util.ZipUtil;
public class TestZip {
public static void main(String[] args) throws Exception {
String srcPathName1 = "C:/Users/sun/Desktop/test1/";
String srcPathName2 = "C:/Users/sun/Desktop/test2/";
String zipPath1 = "C:/Users/sun/Desktop/test1.zip";
String zipPath = "C:/Users/sun/Desktop/test.zip";
ZipUtil.compress(zipPath1,srcPathName1);
ZipUtil.compress(zipPath,srcPathName1,srcPathName2);
String sourceFile = "C:/Users/sun/Desktop/test.zip";
String destDir = "C:/Users/sun/Desktop/test";
ZipUtil.deCompress(sourceFile, destDir);
}
}
java实现单个或多个文件的压缩、解压缩 支持zip、rar等格式的更多相关文章
- Java知多少(73)文件的压缩处理
Java.util.zip 包中提供了可对文件的压缩和解压缩进行处理的类,它们继承自字节流类OutputSteam 和 InputStream.其中 GZIPOutputStream 和 ZipOut ...
- 使用Java API进行tar.gz文件及文件夹压缩解压缩
在java(JDK)中我们可以使用ZipOutputStream去创建zip压缩文件,(参考我之前写的文章 使用java API进行zip递归压缩文件夹以及解压 ),也可以使用GZIPOutputSt ...
- java中自己常用到的工具类-压缩解压zip文件
package com.ricoh.rapp.ezcx.admintoolweb.util; import java.io.File; import java.io.FileInputStream; ...
- 使用PHP对文件进行压缩解压(zip)
使用虚拟主机进行文件上传时最常用的工具莫过于FTP了,但是使用FTP有一个弊端就是文件太多时上传或下载速度比较慢,如果上传时将文件打包,上传后在 空间解压缩,同样下载前将文件打包压缩以压缩包的形式下载 ...
- C# 文件/文件夹压缩解压缩
项目上用到的,随手做个记录,哈哈. 直接上代码: using System; using System.Data; using System.Configuration; using System.C ...
- shell 命令 文件(解)压缩 tar,zip, gzip,bzip2
1.gzip / gunzip [ gzip data.c] 对文件进行压缩,生成 data.c.gz 同时删除了原文件 同时压缩两个文件 [gunzip data.c.gz ...
- php通过文件头检测文件类型通用类(zip,rar…)(转)
在做web应用时候,通过web扩展名判断上存文件类型,这个是我们常使用的.有时候我们这样做还不完善.可能有些人上存一些文件,但是他通过修改 扩展名,让在我们的文件类型之内. 单实际访问时候又不能展示( ...
- linux基础——文件的压缩解压缩以及vim编辑
一.将用户信息数据库文件和组信息数据库文件纵向合并为一个文件/1.txt(覆盖) cat /etc/{passwd,group} > /1.txt 查看:cat /1.txt 二. ...
- JAVA压缩 解压缩zip 并解决linux下中文乱码
1. [代码][Java]代码 1:再压缩前,要设置linux模式, 需要使用第三方ant-1.6.5.jar 如果是文件目录,则ZipEntry zipEntry=new ZipEntry(b ...
随机推荐
- bootstrapTable表格表头换行
使用bootstrapTable组件,达到表头中有一格显示两行,其他表头均为一行,效果图如下: 代码: { field : 'pay_date', title : '已还款完成时间', valign: ...
- Android(java)学习笔记42:Map集合的获取功能
1. Map集合的获取功能: package cn.itcast_01; import java.util.Collection; import java.util.HashMap; import ...
- python:进程操作
一.多进程应用 import socket from multiprocessing import Process def talk(conn): conn.send(b'connected') re ...
- html题型
1.doctype的意义是什么 这个是有历史背景的,在很久以前,IE有一些自己的渲染模式,最典型的就是盒子模型,包括边距.这就造成了不兼容模式,所以他的意义 1)让浏览器以标准模式渲染 2)让浏览器知 ...
- webstorn中的vue文件识别es6代码
webstorn中的vue文件识别es6代码 1.webstorm中es6语法报错,解决方法: 打开 Settings => Languages & Frameworks => J ...
- Android学习笔记_6_保存文件到SDCard
一.加入访问sdcard的权限 Environment.getExternalStorageState()方法用于获取SDCard的状态,如果手机装有SDCard,并且可以进行读写,那么方法返回的状态 ...
- 10474 - Where is the Marble?(模拟)
传送门: UVa10474 - Where is the Marble? Raju and Meena love to play with Marbles. They have got a lot o ...
- Python—面向对象01
1.如何使用类 # 先定义类 class LuffyStudent(): school = "luffycity" # 数据属性 def learn(self): # 函数属性 p ...
- MVC5 数据注解和验证
①利用数据注解进行验证 ②创建自定义的验证逻辑 ③模型元数据注解的用法 ①先创建数据源 1,创建我们的Model Order 2,创建控制器带EF 选择模型为Order 当你运行的时候会报错,需要代 ...
- Xcode DeviceSupport
问题:Could not locate device support files. This iPhone 6s is running iOS 12.1 (16B5059d), which may n ...