当前位置 : 主页 > 编程语言 > c++ >

ZipFileUtil

来源:互联网 收集:自由互联 发布时间:2021-06-30
ZipFileUtil.java package cn.lmy.utils;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;import java.util.zip.ZipOu
ZipFileUtil.java
package cn.lmy.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipFileUtil {

	public static final String entrySplit = "/";
	public static byte[] buff = new byte[8192];

	public synchronized static void unzip(String zipFile, String outDir) throws IOException {
		ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
		ZipEntry ze;
		while ((ze = zis.getNextEntry()) != null) {
			System.out.println(ze.getName());
			File ef = new File(outDir + entrySplit + ze.getName());
			if (ze.isDirectory()) {
				ef.mkdirs();
				continue;
			}
			ef.getParentFile().mkdirs();
			FileOutputStream fis = new FileOutputStream(ef);
			for (int read = zis.read(buff); read > 0; read = zis.read(buff)) {
				fis.write(buff, 0, read);
			}
			fis.close();
		}
		zis.close();
	}

	private static void zip(String workDir, String fileName, ZipOutputStream zos) throws IOException {
		File sourceFile;
		if(workDir != null){
			sourceFile = new File(workDir + entrySplit + fileName);
		}else{
			sourceFile = new File(fileName);
			
		}
		if (!sourceFile.exists()) {
			return;
		}
		ZipEntry ze = new ZipEntry(fileName);
		if (sourceFile.isDirectory()) {
			zos.putNextEntry(new ZipEntry(fileName + entrySplit));
			String[] subFileList = sourceFile.list();
			for (String subFile : subFileList) {
				zip(workDir, fileName + entrySplit + subFile, zos);
			}
		} else {
			zos.putNextEntry(ze);
			FileInputStream fis = new FileInputStream(sourceFile);
			long len = 0;
			for (int read = fis.read(buff); read > 0; read = fis.read(buff)) {
				zos.write(buff, 0, read);
				len += read;
			}
			ze.setSize(len);
			fis.close();
		}
	}

	public synchronized static void zip(String workDir, String[] files, String outZipFile) throws IOException {
		File outFile = new File(outZipFile);
		//outFile.deleteOnExit();
		ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outFile));
		for (String fileName : files) {
			zip(workDir, fileName, zos);
		}
		zos.finish();
		zos.closeEntry();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		String dir = "F:/zip/cn.lmy.util";
		String[] files = new String[] { "dhis", "dhis_new" };
		String outFile = dir + "/apps.zip";
		zip(dir, files, outFile);

		unzip(outFile, dir + "/apps");
	}

}
网友评论