博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java 的zip压缩和解压缩
阅读量:4633 次
发布时间:2019-06-09

本文共 4433 字,大约阅读时间需要 14 分钟。

Java 的zip压缩和解压缩
好久没有来这写东西了,今天中秋节,有个东西想拿出来分享,一来是工作中遇到的问题,一来是和csdn问候一下,下面就分享一个Java中的zip压缩技术,代码实现比较简单,代码如下:
package com.meritit.utils.zip;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;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.io.OutputStream;import java.util.Enumeration;import java.util.zip.ZipEntry;import java.util.zip.ZipException;import java.util.zip.ZipFile;import java.util.zip.ZipOutputStream;/** * @function 实现把指定文件夹下的所有文件压缩为指定文件夹下指定 zip 文件&&实现把指定文件夹下的 zip 文件解压到指定目录下 * @createDate:2013-09-18 * @author Ysjian */public final class ZIPUtils {	/**	 * 测试	 * 	 * @param args	 * @throws IOException 	 * @throws ZipException 	 */	public static void main(String[] args) throws ZipException, IOException {		// 把E:\\Ysjian_Job\\osgistart文件夹下的所有文件压缩到 E:\\test.jar中		zip("E:\\test.xlsx", "E:\\test.jar");		// 把E:\\test.jar 压缩文件内的所有文件解压到 E:\\test目录下面		unZip("E:\\test.jar", "E:\\test");	}	private ZIPUtils() {	}	/**	 * sourceFile 文件进行 zip	 * 格式的压缩,如果sourceFile是目录,就将sourceFile目录下所有的文件及子目录压缩,如果sourceFile是文件	 * ,将sourceFile文件压缩,保存为指定 .zip或者.jar 文件	 * 	 * @param sourceFile	 *            源文件,	 * @param savedFile	 *            保存的文件,可以是.zip或者.jar形式	 * 	 */	public static void zip(String sourceFile, String savedFile) {		ZipOutputStream zos = null;		try {			zos = new ZipOutputStream(new BufferedOutputStream(					new FileOutputStream(savedFile)));			File file = new File(sourceFile);			@SuppressWarnings("unused")			boolean zip = file.isDirectory() ? zipFile(file, file.getPath(),					zos) : zipFile(file, file.getParent(), zos);		} catch (FileNotFoundException e) {			throw new RuntimeException("filePath is invalid-->" + savedFile, e);		} finally {			try {				zos.closeEntry();				zos.close();			} catch (IOException e) {				throw new RuntimeException("fail to close the ZipOutputStream",						e);			}		}	}	/**	 * 压缩文件,利用到了递归	 * 	 * @param source	 * @param basePath	 * @param zos	 * @throws IOException	 */	private static boolean zipFile(File source, String basePath,			ZipOutputStream zos) {		File[] files = null;		if (source.isDirectory()) {			files = source.listFiles();		} else {			files = new File[1];			files[0] = source;		}		String path = null;		byte[] buf = new byte[1024];		int length = 0;		BufferedInputStream bis = null;		try {			for (File file : files) {				if (file.isDirectory()) {					path = file.getPath().substring(basePath.length() + 1)							+ "/";					zos.putNextEntry(new ZipEntry(path));					zipFile(file, basePath, zos);				} else {					path = file.getPath().substring(basePath.length() + 1);					bis = new BufferedInputStream(new FileInputStream(file));					zos.putNextEntry(new ZipEntry(path));					while ((length = bis.read(buf)) > 0) {						zos.write(buf, 0, length);					}				}			}		} catch (Exception e) {			e.printStackTrace();		} finally {			if (bis != null) {				try {					bis.close();				} catch (IOException e) {					throw new RuntimeException(							"fail to close the ZipOutputStream", e);				}			}		}		return true;	}	/**	 * 解压 zip 文件,只能解压标准的 zip文件	 * 	 * @param sourceFile	 *            标准的 zip 文件,不能是把 rar 的直接改为 zip 这样会出现java.io.IOException	 * @param targetDir	 *            存放的目錄	 * @throws ZipException	 * @throws IOException	 */	@SuppressWarnings("resource")	public static void unZip(String sourceFile, String targetDir)			throws ZipException, IOException {		targetDir = targetDir.endsWith("//") ? targetDir : targetDir + "//";		byte b[] = new byte[1024];		ZipFile zipFile = null;		BufferedOutputStream bos = null;		zipFile = new ZipFile(new File(sourceFile));		Enumeration
enumeration = zipFile.entries(); while (enumeration.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) enumeration.nextElement(); File loadFile = new File(targetDir + zipEntry.getName()); if (!zipEntry.isDirectory()) { if (!loadFile.getParentFile().exists()) { loadFile.getParentFile().mkdirs(); } OutputStream os = new FileOutputStream(loadFile); InputStream inputStream = zipFile.getInputStream(zipEntry); bos = new BufferedOutputStream(os); int length = 0; while ((length = inputStream.read(b)) > 0) { bos.write(b, 0, length); } } } }}
最近工作利用了OSGi,需要在代码中手动生成jar包,也就是bundle,所以采用了这种技术去生成jar包。利用了zip压缩,将事先用eclipse生成的bundle的jar包解压出来,在向里面添加自己的文件,然后在压缩成jar。

 

转载于:https://www.cnblogs.com/pangblog/p/3331446.html

你可能感兴趣的文章
tp5+linux+apache php7.1.30环境下,上传图片报错:mkdir():permission denied
查看>>
单片AT89C2051 + SD卡 + 3310LCD = 音乐播放器
查看>>
dp cf 20190615
查看>>
1 线性空间
查看>>
尼克的任务 dp 洛谷1280
查看>>
解决xcode ***is missing from working copy
查看>>
hadoop学习之旅1
查看>>
MVC 中的 ViewModel
查看>>
第四周内容
查看>>
机器学习
查看>>
GTONE清理维护建议方案
查看>>
[bbk4967]第73集 第9章 -数据库性能维护 00
查看>>
Noip2017 跳房子——普及组
查看>>
begin.lydsy 入门OJ题库:1104:纯粹合数
查看>>
builder-theory.cs
查看>>
如何使用JPA注解标注多对多的关系
查看>>
Cassandra 1.2 发布,NoSQL 数据库
查看>>
DataCleaner 3.1.1 发布,数据质量分析管理
查看>>
不同的source control下配置DiffMerge
查看>>
memcached和redis的区别和应用场景
查看>>