deflate and inflate simple demo (ZipInputStream/ZipOutputStream)

吴伟志
2023-12-01
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.Checksum;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;


public class DeflateUtil {
	/**
	 * 
	 * @param source	待压缩文件的路径
	 * @param target	产出的压缩文件的文件名
	 * @return
	 * @throws Exception
	 */
	public static Checksum deflate(String[] source,String target) throws Exception{
		FileOutputStream fos = new FileOutputStream(target);
		CheckedOutputStream csum = new CheckedOutputStream(fos,new Adler32());
		ZipOutputStream zos = new ZipOutputStream(csum);
		BufferedOutputStream out = new BufferedOutputStream(zos);
		
		for(String filename:source){
			File file = new File(filename);
			FileInputStream in = new FileInputStream(file);
			
			zos.putNextEntry(new ZipEntry(file.getName()));
			
			byte[] buffer = new byte[1024*100];
			int len = -1;
			while( (len =  in.read(buffer) ) != -1){
				out.write(buffer,0,len);
			}
			in.close();
			out.flush();
		}
		
		out.close();

		return csum.getChecksum();
	}
	/**
	 * 
	 * @param source	待解压文件路径
	 * @param path		解压到这个路径下
	 * @return
	 * @throws Exception
	 */
	public static Checksum inflate(String source,String path) throws Exception{
		FileInputStream fis = new FileInputStream(source);
		CheckedInputStream csum = new CheckedInputStream(fis,new Adler32());
		ZipInputStream zis = new ZipInputStream(csum);
		BufferedInputStream in = new BufferedInputStream(zis);
		ZipEntry ze = null;
		
		while((ze = zis.getNextEntry()) != null){
			FileOutputStream out = new FileOutputStream(path+"\\"+ze.getName());
			
			byte[] buffer = new byte[1024 * 100];
			int len = -1;
			while( ( len = in.read(buffer) ) != -1 ){
				out.write(buffer, 0, len);
			}
			out.close();
		}
		in.close();
		return csum.getChecksum();
	}
}


 类似资料: