Android加压和解压zip文件

这里介绍一个Andorid解压和加压zip文件的实例。不多说了直接上代码:

public static void zip(String src, String dest) throws IOException {

// 提供了一个数据项压缩成一个ZIP归档输出流
ZipOutputStream out = null;


try {

File outFile = new File(dest);// 源文件或者目录
File fileOrDirectory = new File(src);// 压缩文件路径
out = new ZipOutputStream(new FileOutputStream(outFile));
// 如果此文件是一个文件,否则为false。


if (fileOrDirectory.isFile()) {


zipFileOrDirectory(out, fileOrDirectory, "");


} else {


// 返回一个文件或空阵列。
File[] entries = fileOrDirectory.listFiles();
for (int i = 0; i < entries.length; i++) {
// 递归压缩,更新curPaths
zipFileOrDirectory(out, entries[i], "");
}
}


} catch (IOException ex) {


ex.printStackTrace();


} finally {


// 关闭输出流
if (out != null) {


try {

out.close();


} catch (IOException ex) {


ex.printStackTrace();
}
}
}
}

private static void zipFileOrDirectory(ZipOutputStream out,
File fileOrDirectory, String curPath) throws IOException {
// 从文件中读取字节的输入流
FileInputStream in = null;
try {
// 如果此文件是一个目录,否则返回false。
if (!fileOrDirectory.isDirectory()) {
// 压缩文件
byte[] buffer = new byte[4096];
int bytes_read;
in = new FileInputStream(fileOrDirectory);
// 实例代表一个条目内的ZIP归档
ZipEntry entry = new ZipEntry(curPath
+ fileOrDirectory.getName());
// 条目的信息写入底层流
out.putNextEntry(entry);
while ((bytes_read = in.read(buffer)) != -1) {
out.write(buffer, 0, bytes_read);
}
out.closeEntry();
} else {
// 压缩目录
File[] entries = fileOrDirectory.listFiles();
for (int i = 0; i < entries.length; i++) {
// 递归压缩,更新curPaths
zipFileOrDirectory(out, entries[i], curPath
+ fileOrDirectory.getName() + "/");
}
}
} catch (IOException ex) {
ex.printStackTrace();
// throw ex;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

/

上面是加压zip文件的实例,本博客实例Demo工程代码地址:http://download.csdn.net/detail/u010739551/7394859

工程Demo代码包含了解压zip文件和加压zip文件的全部代码


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值