• Java 的zip压缩和解压缩


    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。

  • 相关阅读:
    Modernizr使用指南(转)
    使用Func<>和Action简化委托
    实现类似MVC ViewBag类型的对象
    更改服务器的SID 加入域控制器提示SID重复
    SQL SERVER 执行大于80M的SQL 脚本
    完全关闭IIS日志,包括System32下的LogFile
    MVC不用302跳转Action,内部跳转
    SHA1l加密
    获取当前时间戳
    invoke反射
  • 原文地址:https://www.cnblogs.com/pangblog/p/3331446.html
Copyright © 2020-2023  润新知