java向压缩文件添加文件

package org.alfresco.repo.bom.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.Deflater;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

public class AppendFileToCompressedFileUtil {
	
	private static final String compressedFilePath = "F:/chiang.zip";
	private static final String newCompressedFilePath = "F:/tdp.zip";
	private static final String appendFilePackage = "data";
	
	public void append(String appendFile) throws Exception{
		ZipOutputStream zos = null;
		InputStream input = null;
		File newCompressedFile = new File(newCompressedFilePath); 
		if (newCompressedFile.exists()) { 
			newCompressedFile.delete(); 
		}
		try {
			ZipFile compressedFile = new ZipFile(compressedFilePath, "GBK");
			//System.out.println(compressedFile.getEncoding());
			zos = new ZipOutputStream(new FileOutputStream(newCompressedFilePath));
			zos.setEncoding("GBK");
			zos.setComment("Bale tdp!");
			zos.setLevel(Deflater.BEST_COMPRESSION);
			zos.setMethod(Deflater.DEFLATED);
			//
			if (!"".equals(appendFile)) {
				File f = new File(appendFile);
				ZipEntry pag = new ZipEntry(appendFilePackage+f.separator);
				zos.putNextEntry(pag);
				ZipEntry fileEntry = new ZipEntry(appendFilePackage+f.separator+f.getName());
				zos.putNextEntry(fileEntry);
				input = new FileInputStream(f);
				startCopy(zos, input);
			}
			Enumeration<? extends ZipEntry> e = compressedFile.getEntries();
			while (e.hasMoreElements()) {
				ZipEntry entry = e.nextElement();
				zos.putNextEntry(entry);
				if (!entry.isDirectory()) {
					startCopy(zos, compressedFile.getInputStream(entry));
				}
				zos.closeEntry();
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(zos!=null)
				zos.close();
		}
	}
	
	public void startCopy(ZipOutputStream zos,InputStream input) throws Exception{
		int data = 0 ;
		try {
			while ((data=input.read())!=-1) {
				zos.write(data);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(input!=null)
				input.close();
		}
	}
	// main test method
	public static void main(String[] args) throws Exception{
		AppendFileToCompressedFileUtil a = new AppendFileToCompressedFileUtil();
		String append = "F:/你现在好吗.txt";
		a.append(append);
	}
}

猜你喜欢

转载自chiangfai.iteye.com/blog/2251894