java 压缩文件夹(包含内容)

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

public class zip {
	public static void compressAllZip(String dirpath, String srcName, String targerName) {
		if (dirpath == null) {
			System.out.print("no");
			return;
		}
		File baseDir = new File(dirpath);
		if (!baseDir.exists() || (!baseDir.isDirectory())) {
			System.out.print("no");
			return;
		}
		String basicRootdir = baseDir.getAbsolutePath();
		File targerFile = new File(targerName);
		try {
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(targerFile));
			if (srcName.equals("*")) {
zip.commpressDirToZip(basicRootdir, baseDir, out);
			}else {
				File file=new File(baseDir,srcName);
				if(file.isFile()){
					zip.compressfiletozip(basicRootdir, file, out);
				}else {
					zip.commpressDirToZip(basicRootdir, file, out);
				}
			}
			out.close();
			System.out.print("ok");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	private static void commpressDirToZip(String basicrootdir, File dir, ZipOutputStream out) {
		if (dir.isDirectory()) {
			File [] files=dir.listFiles();
			if(files.length==0){
				ZipEntry entry=new ZipEntry(getfilename(basicrootdir,dir));
				try {
					out.putNextEntry(entry);
					out.closeEntry();
				} catch (Exception e) {
					// TODO: handle exception
				}
				return ;
			}
			for(int i=0;i

你可能感兴趣的:(java)