`
cnetwei
  • 浏览: 174308 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

使用Java操作zip文件

阅读更多

使用Java操作zip文件

 

 

Java提供了操作zip文件的API,具体来说,它们位于:java.util.zip 包中,以下的两个工具类分别用于创建zip文件、展开(解压缩)zip文件。

 

创建zip文件的助手类:

/**
 * @author INC062805
 * 
 */
public class ZipHelper {
	// 静态创建起
	public static ZipHelper create(File input, File output) {
		// 检查参数
		if (input == null || !input.exists()) {
			throw new IllegalArgumentException("input is NULL or not exist!");
		}
		if (output == null) {
			throw new IllegalArgumentException("output can not be NULL!");
		}

		return new ZipHelper(input, output);
	}

	// 隐藏构建器
	ZipHelper(File input, File output) {
		this.input = input;
		this.output = output;
	}

	// 开始执行压缩
	public boolean start() {
		OutputStream out = null;
		try {
			out = new BufferedOutputStream(new FileOutputStream(output));
			ZipOutputStream zipOut = new ZipOutputStream(out);

			zipOut.setLevel(ZipEntry.STORED);
			zip(zipOut, input, input);

			zipOut.flush();
			zipOut.finish();
			zipOut.close();

			return true;
		} catch (Exception e) {
			// e.printStackTrace();
			return false;
		} finally {
			IOUtils.quietCloseOutputStream(out);
		}
	}

	// 执行压缩,input:输入文件(可以是目录),rootDir:起始目录
	private void zip(ZipOutputStream out, File input, File rootDir)
			throws IOException {
		if (input == null || !input.exists()) {
			return;
		}
		if (input.isDirectory()) {
			zipDirectory(out, input, rootDir);
		} else {
			zipFile(out, input, rootDir);
		}

	}

	// 向ZipOutputStream中添加目录,dir:输入目录,rootDir:起始目录
	private void zipDirectory(ZipOutputStream out, File dir, File rootDir)
			throws IOException {
		// 检查input目录,是否是系统顶级目标,例如:c:\ or /
		if (rootDir.getParentFile() == null) {
			// SKIP ROOT DIR
		}

		if (!onlyFile) {
			String name = getEntryNameString(dir, rootDir) + '/';
			out.putNextEntry(new ZipEntry(name));
			// System.out.println("zip.dir:" + entry.getName());
		}

		File[] files = dir.listFiles();
		for (File f : files) {
			zip(out, f, rootDir);
		}
	}

	// 向ZipOutputStream中 添加文件
	private void zipFile(ZipOutputStream out, File file, File rootDir)
			throws IOException {
		//
		ZipEntry entry = new ZipEntry(getEntryNameString(file, rootDir));
		out.putNextEntry(entry);

		InputStream in = null;
		try {
			in = new FileInputStream(file);
			IOUtils.copy(in, out);
			out.closeEntry();
			// System.out.println("zip.file:" + entry.getName());
		} finally {
			IOUtils.quietCloseInputStream(in);
		}
	}

	// 通过输入文件(名称),取得在Zip Entry中应该有的名称
	private String getEntryNameString(final File input, final File rootDir) {
		if (onlyFile) {
			return input.getName();
		}

		// 检查是否是root
		if (input.equals(rootDir)) {
			return input.getName();
		}

		// 确认回溯前的起始位置
		final File parent = rootDir.getParentFile();
		File file = input;

		// 回溯 直到找到 root
		StringBuilder ret = new StringBuilder();
		do {
			if (ret.length() > 0) {
				ret.insert(0, '/');
			}
			ret.insert(0, file.getName());
			file = file.getParentFile();

		} while (file != null && !file.equals(parent));

		return ret.toString();
	}

	// 是否更新已存在的输出文件
	// private boolean update = false;
	// 是否仅仅打包文件,忽略目录结构
	private boolean onlyFile = false;
	// 输入输出
	private final File input;
	private final File output;

	public boolean isOnlyFile() {
		return onlyFile;
	}

	public void setOnlyFile(boolean onlyFile) {
		this.onlyFile = onlyFile;
	}
}
 

展开zip文件的助手类:

/**
 * @author INC062805
 * 
 *         展开zip文件的助手类
 */
public class UnZipHelper {
	//
	public static UnZipHelper create(File srcZipFile, File destDir) {
		return new UnZipHelper(srcZipFile, destDir);
	}

	//
	private File srcZipFile, destDir;
	private CharSequence error = null;

	// 隐藏构建器
	private UnZipHelper(File srcZipFile, File destDir) {
		this.srcZipFile = srcZipFile;
		this.destDir = destDir;
	}

	// 取得错误信息
	public CharSequence getErrorInfo() {
		return error;
	}

	// 展开src 指定的zip文件到 目标位置dest
	public boolean start() {
		return start(true);
	}

	// 展开src 指定的zip文件到 目标位置dest,并自动创建顶级目录
	public boolean start(boolean autoCreateTopDir) {
		// 自动创建顶级目录 --- 与zip文件同名
		if (autoCreateTopDir) {
			String name = srcZipFile.getName();

			// 析除扩展名
			int pos = name.lastIndexOf('.');
			if (pos > 0) {
				name = name.substring(0, pos);
			}

			destDir = new File(destDir, name);
			destDir.mkdirs();
		}

		try {
			ZipFile zf = new ZipFile(srcZipFile);
			Enumeration<? extends ZipEntry> e = zf.entries();
			boolean bool = false;
			while (e.hasMoreElements()) {
				ZipEntry ze = e.nextElement();
				// 处理目录
				if (ze.isDirectory()) {
					bool = expandDirectory(ze, destDir);
					continue;
				}
				// 处理文件
				bool = expandFile(zf, ze, destDir);
			}
			return bool;
		} catch (Exception e) {
			error = "open zipfile Error:(" + e.getLocalizedMessage() + ")";
			return false;
		}
	}

	// 解压缩目录元素 到目标位置
	private boolean expandDirectory(ZipEntry ze, File destDir) {
		File dir = new File(destDir, ze.getName());
		boolean bool = dir.exists() ? true : dir.mkdirs();
		// System.out.println("Expand.Dir:" + dir.getAbsolutePath());
		if (!bool) {
			error = "create Dest Directory Error,:-(";
		}
		return bool;
	}

	// 解压缩文件元素到目标目录下
	private boolean expandFile(ZipFile zf, ZipEntry ze, File destDir) {
		// 定位到目标目录
		String name = ze.getName();
		File dir = locateDestDirectory(name, destDir);

		// 确认目标文件位置
		int pos = name.lastIndexOf('/');
		if (pos > 0) {
			name = name.substring(pos + 1);
		}

		// 从zip 输入流中创建 目标文件
		return makeFile(new File(dir, name), zf, ze);
	}

	// 定位目标实体的所在目录
	private File locateDestDirectory(String path, File destDir) {
		File dir = destDir;
		int pos = path.indexOf('/');
		while (pos > 0) {
			dir = new File(dir, path.substring(0, pos));
			path = path.substring(pos + 1);
			pos = path.indexOf('/');
		}
		return dir;
	}

	//
	private boolean makeFile(File file, ZipFile zf, ZipEntry ze) {
		OutputStream out = null;
		InputStream in = null;
		try {
			//
			boolean bool = file.exists() ? true : file.createNewFile();
			// System.out.println("create New File:" + bool);
			if (!bool) {
				error = "createNewFile.Error,:-(";
				return false;
			}

			//
			out = new BufferedOutputStream(new FileOutputStream(file));
			in = zf.getInputStream(ze);

			// long len =
			IOUtils.copy(in, out);
			// System.out.println("make New File length:" + len);
			return true;
		} catch (Exception e) {
			error = "makeFile.Error:(" + e.getLocalizedMessage() + ")";
			return false;
		} finally {
			IOUtils.quietCloseOutputStream(out);
			IOUtils.quietCloseInputStream(in);
		}
	}
}
 

参考资料:

解决Zip文件中文名问题

http://www.cnblogs.com/CUCmehp/archive/2008/10/28/1320872.html


加密,解密zip文件、对称加密,RSA,AES算法

http://hi.baidu.com/yezongbo/blog/item/1b7960fd6aae661308244d14.html


除了Java平台本身提供的API之外,我还发现一个开源的项目,Truezip (http://truezip.java.net/)有机会再研究吧。

 

附件是两个助手类文件,可下载使用(将.png后缀删除即可):

ZipHelper.javaUnZipHelper.java

  • 大小: 3.9 KB
  • 大小: 3.8 KB
分享到:
评论

相关推荐

    java 操作Zip文件(压缩、解压、加密).zip

    java 操作Zip文件(压缩、解压、加密) zip4j-1.3.2.jar ant-1.10.6.jar

    zip4j--Java操作zip压缩文件接口

    Java操作zip压缩格式的开源项目,功能强大而且使用方便,能完全满足Java操作Zip压缩文件,官方网址为:http://www.lingala.net/zip4j/ 可以下载到jar包、源码和示例,好像没有提供API文档。 不过需要使用代理访问...

    Java操作ZIP文件,支持密码和中文

    winszipaes是Java语言下的ZIP文件操作接口,支持密码,但源代码不支持中文,该jar包对源码作了一点修改,使其支持中文,修改信息可以参照我的博客http://blog.csdn.net/zhangyihui1986/article/details/7724229或者...

    Java调用Zip类批量压缩多个文件.rar

    Java调用Zip类批量压缩多个文件,此前有一个是压缩单个文件,也可参考,相关代码中可找到此源码。  public class ZipDemo extends JFrame{  JFileChooser fileChooser; //文件选择器  JList fileList; //待...

    java操作共享文件

    java读取共享文件使用jcifs-1.1.11.jar 的SmbFile 类使用用户名密码共享目录操作共享文件

    zip4j_1.3.2 - Java操作zip压缩文件接口最新版本

    Java操作zip压缩格式的开源项目,功能强大而且使用方便,能完全满足Java操作Zip压缩文件,官方网址为:http://www.lingala.net/zip4j/ 可以下载到jar包、源码和示例,好像没有提供API文档。 不过需要使用代理访问...

    Java实现Zip压缩文件操作的工具类.zip

    Java实现Zip压缩文件操作的工具类 文章介绍:https://blog.csdn.net/rongbo91/article/details/117747042 (可作为Jar依赖包直接使用) 1、项目使用前,请进入rdc-bom目录下,执行mvn clean install命令  2、可...

    Java实现将多目录多层级文件打成ZIP包,以及解压ZIP包

    包含了使用的jar包,以及一个Java类,实现了使用Java对多目录多层级的文件进行打包,以及对ZIP包进行解压缩的操作。

    用Java压缩解压ZIP文件

    用Java压缩解压ZIP文件,将利用java.util.zip 包中提供的类来实现压缩和解压zip 格式文件的功能。当然,本例在功能上完全没有Winzip 等成熟的压缩软件那么强,也不能做的很强,本例仅仅是演示如何来使用java.util....

    java操作zip_包括加解密码

    java将文件压缩成ZIP格式的工具包API,操作简捷。 内附源码、文档、用例。

    java将文件夹压缩成zip,解压zip压缩包

    java控制指定路径下的文件夹压缩成zip格式。 java将zip压缩包解压成为文件夹。直接使用io流进行操作,不需借助其他jar包

    JAVA 文件常用流操作.zip

    JAVA 文件常用流操作 包括文件的创建,重命名,删除等等。字节流,字符流,缓存流,数据流,打印流,内存流等等

    java,Blob字段操作,将图片或者文件保存到数据库中.zip

    java,Blob字段操作,将图片或者文件保存到数据库中.zip

    Java使用winzipaes对zip文件的操作,支持中文

    winzipaes是Java操作ZIP文件的开源项目,支持密码,但不支持中文文件名。此文件中包含修改后的源码、文档、jar包、依赖包及示例程序等文件。可以压缩文件名含有中文的文件,修改之处可以参看博客...

    java.util.zip 解压缩文件,ZIP格式压缩文件.rar

    Java解压缩文件,并以ZIP格式压缩文件,主要是使用java.util.zip 包中的类来实现解压、压缩文件功能,如果你对这个类并不太熟悉,你正好可以参考一下这个类是如何用的。

    Java对zip文件的操作winzipaes源码,支持中文

    winzipaes是Java操作ZIP文件的开源项目,支持密码,但不支持中文文件名,此文件中是修改后的源码,可以压缩文件名含有中文的文件,修改之处可以参看博客http://xjlsgcjdtc.iteye.com/blog/1439514或者...

    Java压缩和解压缩zip文件

    这几天做一个操作docx的文档的功能,Apache的POI功能有限,就参考了相关资料写的一个Java压缩和解压zip文件的工具类。全部使用的是Java自带的类库,中文的文件名会有乱码的问题。

    java操作压缩文件和解压文件实例代码(经测试)

    java操作压缩文件和解压文件实例代码(经测试),把jar文件导入到项目里。源代码根据注释修改下路径就能用了

    js上传zip文件java解压.txt

    jsp页面上传zip压缩包,用ajax传给后端进行解压,创建路径解压存储在本地,然后程序调用解压后的文件进行操作,然后再删除临时文件夹。用于批量导入信息和照片,然后ajax回调导入结果返回前端显示给操作者。

    Java流(文件读写操作)

    一、 流的分类 • 按数据流动方向 – 输入流:只能从中读取字节数据,而不能向其写出数据 – 输出流:只能向其写入字节数据,而不能从中读取数据 • 按照流所处理的数据类型 – 字节流:用于处理字节数据。...

Global site tag (gtag.js) - Google Analytics