转载请注明出处:http://blog.csdn.net/y22222ly/article/details/52201675

zip压缩,解压

zip压缩与解压主要依靠java api的两个类:

ZipInputStream

ZipOutputStream

做了一个简单的封装.

使用方法:

        try {
ZipUtil.compress(getSDCard() + "zipTest", getSDCard() + "zipTest.zip");
ZipUtil.decompress(getSDCard() + "zipTest.zip", getSDCard() + "zipTestFolder");
} catch (Exception e) {
e.printStackTrace();//失败
}

工具类ZipUtil:

package com.raise.raisestudy.zip;

import android.text.TextUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream; /**
* zip文件加压解压原理如下
* compress @see {@link ZipOutputStream}
* * <pre>
* OutputStream os = ...
* ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(os));
* try {
* for (int i = 0; i < fileCount; ++i) {
* String filename = ...
* byte[] bytes = ...
* ZipEntry entry = new ZipEntry(filename);
* zos.putNextEntry(entry);
* zos.write(bytes);
* zos.closeEntry();
* }
* } finally {
* zos.close();
* }
* </pre>
* decompress @see {@link ZipInputStream}
* <pre>
* InputStream is = ...
* ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
* try {
* ZipEntry ze;
* while ((ze = zis.getNextEntry()) != null) {
* ByteArrayOutputStream baos = new ByteArrayOutputStream();
* byte[] buffer = new byte[1024];
* int count;
* while ((count = zis.read(buffer)) != -1) {
* baos.write(buffer, 0, count);
* }
* String filename = ze.getName();
* byte[] bytes = baos.toByteArray();
* // do something with 'filename' and 'bytes'...
* }
* } finally {
* zis.close();
* }
* </pre>
* 支持空文件夹加压解压
* Created by raise.yang on 16/08/09.
*/
public class ZipUtil { private static final String TAG = "ZipUtil"; /**
* 解压文件到指定文件夹
*
* @param zip 源文件
* @param destPath 目标文件夹路径
* @throws Exception 解压失败
*/
public static void decompress(String zip, String destPath) throws Exception {
//参数检查
if (TextUtils.isEmpty(zip) || TextUtils.isEmpty(destPath)) {
throw new IllegalArgumentException("zip or destPath is illegal");
}
File zipFile = new File(zip);
if (!zipFile.exists()) {
throw new FileNotFoundException("zip file is not exists");
}
File destFolder = new File(destPath);
if (!destFolder.exists()) {
if (!destFolder.mkdirs()) {
throw new FileNotFoundException("destPath mkdirs is failed");
}
}
ZipInputStream zis = null;
BufferedOutputStream bos = null;
try {
zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zip)));
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
//得到解压文件在当前存储的绝对路径
String filePath = destPath + File.separator + ze.getName();
if (ze.isDirectory()) {
new File(filePath).mkdirs();
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
while ((count = zis.read(buffer)) != -1) {
baos.write(buffer, 0, count);
}
byte[] bytes = baos.toByteArray();
File entryFile = new File(filePath);
//创建父目录
if (!entryFile.getParentFile().exists()) {
if (!entryFile.getParentFile().mkdirs()) {
throw new FileNotFoundException("zip entry mkdirs is failed");
}
}
//写文件
bos = new BufferedOutputStream(new FileOutputStream(entryFile));
bos.write(bytes);
bos.flush();
} }
} finally {
closeQuietly(zis);
closeQuietly(bos);
}
} /**
* @param srcPath 源文件的绝对路径,可以为文件或文件夹
* @param destPath 目标文件的绝对路径 /sdcard/.../file_name.zip
* @throws Exception 解压失败
*/
public static void compress(String srcPath, String destPath) throws Exception {
//参数检查
if (TextUtils.isEmpty(srcPath) || TextUtils.isEmpty(destPath)) {
throw new IllegalArgumentException("srcPath or destPath is illegal");
}
File srcFile = new File(srcPath);
if (!srcFile.exists()) {
throw new FileNotFoundException("srcPath file is not exists");
}
File destFile = new File(destPath);
if (destFile.exists()) {
if (!destFile.delete()) {
throw new IllegalArgumentException("destFile is exist and do not delete.");
}
} CheckedOutputStream cos = null;
ZipOutputStream zos = null;
try {
// 对目标文件做CRC32校验,确保压缩后的zip包含CRC32值
cos = new CheckedOutputStream(new FileOutputStream(destPath), new CRC32());
//装饰一层ZipOutputStream,使用zos写入的数据就会被压缩啦
zos = new ZipOutputStream(cos);
zos.setLevel(9);//设置压缩级别 0-9,0表示不压缩,1表示压缩速度最快,9表示压缩后文件最小;默认为6,速率和空间上得到平衡。
if (srcFile.isFile()) {
compressFile("", srcFile, zos);
} else if (srcFile.isDirectory()) {
compressFolder("", srcFile, zos);
}
} finally {
closeQuietly(zos);
}
} private static void compressFolder(String prefix, File srcFolder, ZipOutputStream zos) throws IOException {
String new_prefix = prefix + srcFolder.getName() + "/";
File[] files = srcFolder.listFiles();
//支持空文件夹
if (files.length == 0) {
compressFile(prefix, srcFolder, zos);
} else {
for (File file : files) {
if (file.isFile()) {
compressFile(new_prefix, file, zos);
} else if (file.isDirectory()) {
compressFolder(new_prefix, file, zos);
}
}
}
} /**
* 压缩文件和空目录
*
* @param prefix
* @param src
* @param zos
* @throws IOException
*/
private static void compressFile(String prefix, File src, ZipOutputStream zos) throws IOException {
//若是文件,那肯定是对单个文件压缩
//ZipOutputStream在写入流之前,需要设置一个zipEntry
//注意这里传入参数为文件在zip压缩包中的路径,所以只需要传入文件名即可
String relativePath = prefix + src.getName();
if (src.isDirectory()) relativePath += "/";//处理空文件夹
ZipEntry entry = new ZipEntry(relativePath);
//写到这个zipEntry中,可以理解为一个压缩文件
zos.putNextEntry(entry);
InputStream is = null;
try {
if (src.isFile()) {
is = new FileInputStream(src);
byte[] buffer = new byte[1024 << 3];
int len = 0;
while ((len = is.read(buffer)) != -1) {
zos.write(buffer, 0, len);
}
}
//该文件写入结束
zos.closeEntry();
} finally {
closeQuietly(is);
}
} private static void closeQuietly(final Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (final IOException ioe) {
// ignore
}
}
}

GZip压缩,解压

GZip压缩与解压主要依靠java api的两个类:

GZipInputStream

GZipOutputStream

做了一个简单的封装.

使用方法:

        try {
ZipUtil.compress(getSDCard() + "zipTest", getSDCard() + "zipTest.zip");
ZipUtil.decompress(getSDCard() + "zipTest.zip", getSDCard() + "zipTestFolder");
} catch (Exception e) {
e.printStackTrace();//失败
}

工具类GZipUtil.java

package com.raise.raisestudy.zip;

import android.text.TextUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream; /**
* compress @see {@link GZIPOutputStream}
* <pre>
* OutputStream os = ...
* byte[] bytes = ...
* GZIPOutputStream zos = new GZIPOutputStream(new BufferedOutputStream(os));
* try {
* zos.write(bytes);
* } finally {
* zos.close();
* }
* </pre>
* <p>
* compress @see {@link GZIPInputStream}
* <pre>
* InputStream is = ...
* GZIPInputStream zis = new GZIPInputStream(new BufferedInputStream(is));
* try {
* // Reading from 'zis' gets you the uncompressed bytes...
* processStream(zis);
* } finally {
* zis.close();
* }
* </pre>
* <p>
* Created by raise.yang on 16/08/13.
*/ public class GZipUtil { /**
* 解压文件到指定文件夹
*
* @param gzip 源文件
* @param destPath 目标文件绝对路径
* @throws Exception 解压失败
*/
public static void decompress(String gzip, String destPath) throws Exception {
//参数检查
if (TextUtils.isEmpty(gzip) || TextUtils.isEmpty(destPath)) {
throw new IllegalArgumentException("gzip or destPath is illegal");
}
File gzipFile = new File(gzip);
if (!gzipFile.exists()) {
throw new FileNotFoundException("gzip file is not exists");
}
File destFile = new File(destPath);
if (destFile.exists()) {
if (!destFile.delete()) {
throw new FileNotFoundException("destFile delete is failed");
}
} GZIPInputStream zis = null;
BufferedOutputStream bos = null;
try {
zis = new GZIPInputStream(new BufferedInputStream(new FileInputStream(gzipFile)));
bos = new BufferedOutputStream(new FileOutputStream(destPath));
byte[] buffer = new byte[1024 << 3];
int len = 0;
while ((len = zis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.flush();
} finally {
closeQuietly(zis);
closeQuietly(bos);
}
} /**
* @param srcPath
* @param destPath
* @throws Exception
*/
public static void compress(String srcPath, String destPath) throws Exception {
//参数检查
if (TextUtils.isEmpty(srcPath) || TextUtils.isEmpty(destPath)) {
throw new IllegalArgumentException("srcPath or destPath is illegal");
}
File srcFile = new File(srcPath);
if (!srcFile.exists() || srcFile.isDirectory()) {
throw new FileNotFoundException("srcPath file is not exists");
}
File destFile = new File(destPath);
if (destFile.exists()) {
if (!destFile.delete()) {
throw new IllegalArgumentException("destFile is exist and do not delete.");
}
}
GZIPOutputStream zos = null;
InputStream is = null;
try {
zos = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(destPath)));
is = new FileInputStream(srcFile);
byte[] buffer = new byte[1024 << 3];
int len = 0;
while ((len = is.read(buffer)) != -1) {
zos.write(buffer, 0, len);
}
zos.flush();
} finally {
closeQuietly(is);
closeQuietly(zos);
}
} private static void closeQuietly(final Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (final IOException ioe) {
// ignore
}
}
}

参考文章:http://www.importnew.com/14410.html

Java_压缩与解压工具类的更多相关文章

  1. 文件压缩、解压工具类。文件压缩格式为zip

    package com.JUtils.file; import java.io.BufferedOutputStream; import java.io.File; import java.io.Fi ...

  2. GZip 压缩解压 工具类 [ GZipUtil ]

    片段 1 片段 2 pom.xml <dependency> <groupId>commons-codec</groupId> <artifactId> ...

  3. Zip包解压工具类

    最近在做项目的自动检测离线升级,使用到了解压zip包的操作,本着拿来主义精神,搞了个工具类(同事那边拿的),用着还不错. package com.winning.polaris.admin.utils ...

  4. zip文件解压工具类

    java解压zip文件 import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io. ...

  5. Linux打包压缩解压工具

    第1章      Linux 打包压缩解压工具一.压缩.解压工具 compress/uncompress gzip/gunzip bzip2/bunzip2/ bzcat xz/unxz/ xzcat ...

  6. XML序列化 判断是否是手机 字符操作普通帮助类 验证数据帮助类 IO帮助类 c# Lambda操作类封装 C# -- 使用反射(Reflect)获取dll文件中的类型并调用方法 C# -- 文件的压缩与解压(GZipStream)

    XML序列化   #region 序列化 /// <summary> /// XML序列化 /// </summary> /// <param name="ob ...

  7. 文件操作工具类: 文件/目录的创建、删除、移动、复制、zip压缩与解压.

    FileOperationUtils.java package com.xnl.utils; import java.io.BufferedInputStream; import java.io.Bu ...

  8. 使用SharpZIpLib写的压缩解压操作类

    使用SharpZIpLib写的压缩解压操作类,已测试. public class ZipHelper { /// <summary> /// 压缩文件 /// </summary&g ...

  9. Android 打造自己的个性化应用(五):仿墨迹天气实现续--> 使用Ant实现zip/tar的压缩与解压

    上一篇中提到对于Zip包的解压和压缩需要借助Ant 实现,我经过参考了其他的资料,整理后并加上了一些自己的看法: 这里就具体地讲下如何使用Ant进行解压缩及其原因: java中实际是提供了对  zip ...

随机推荐

  1. javascript中的事件问题的总结

    一.什么是事件? 事件就是DOM和浏览器之间的交互行为(只要触发了这个行为,也就相当于触发了事件),我们可以通过事件监听来绑定事件,例如:box.onclick=function(){},如果我们点击 ...

  2. (转)Windows Server 2012 R2虚拟机自激活(AVMA)技术

    转自: 老丁的技术博客 相信Hyper-v管理员都有这样的经历,安装多台虚拟机后,都要一台一台手工激活,如果虚拟机足够多的话,这是一项很繁琐的工作,但从Windows Server 2012 R2开始 ...

  3. ubuntu,右键添加在终端中打开

    右键中添加"在终端中打开" 在终端输入  sudo apt-get install nautilus-open-terminal 重新启动, 进入操作系统就会发现单击鼠标右键就会出 ...

  4. Cmake 实现debug和release lib依赖项处理

    一.说明 最近用cmake开发东西,编译vs时候,发现debug和release版本的lib库的依赖项问题,故此小结一下.若有不对之处,还请看官多多指教. 使用的工程有自己编写的工程,也有借用第三方库 ...

  5. POJ 2642 The Brick Stops Here 0-1背包

    poj: http://poj.org/problem?id=2642 大意: 给出n(n<=200)块黄铜合金,还有它们的浓度和价钱.给出若干个个询问使它们在n块中取 M 块 使得这M块合金的 ...

  6. 无法顺利删除问题处理一则-ORA-00604和ORA-00942错误

    1.以sys/oracle登录 2. -- Create tablecreate table ARGUMENT$(  OBJ#          NUMBER not null,  PROCEDURE ...

  7. 【例题3-3 UVA - 401】Palindromes

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 如果一个字符没有对应的镜像,那么它对应的是一个空格. 然后注意 aba这种情况. 这种情况下b也要查一下它的镜像是不是和b一样. [ ...

  8. JAVA Concurrent包 中的并发集合类

    我们平时写程序需要经常用到集合类,比如ArrayList.HashMap等,但是这些集合不能够实现并发运行机制,这样在服务器上运行时就会非常的消耗资源和浪费时间,并且对这些集合进行迭代的过程中不能进行 ...

  9. arm Linux 如何自动检测并mount SD卡,以及如何得知已经mount

    一.土八路做法: SD 卡一旦插入系统,内核会自动在/dev/下创建设备文件:sdcard. 但有时可能时用户在拨出卡前并没有umount的话,第二次插卡进去后系统创建的就不是sdcard设备文件了, ...

  10. Linux 下查看线程信息

    1. 使用 pstree -p PID ps aux | grep firefox | grep -v grepcharles  26058  0.0  0.0   4908  1152 ?      ...