Java压缩文件/目录成ZIP包(解决中文问题)

使用Java自带的类 java.util.zip进行文件/目录的压缩的话,有一点不足,不支持中文的名件/目录命名,如果有中文名,那么打包就会失败。本人经过一段时间的摸索和实践,发现在一般的Ant.jar类库中也有zip类,import org.apache.tools.zip.*,能够解决不支持中文文件目录的问题,同时,Ant的获得途径也比较多,一般的应用服务器中有这个包,实在不行去下载个tomcat5.X,里面也有ant.jar,本人经过测试,可以使用。

 

import java.io.File;
import org.apache.tools.zip.ZipOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
 * 
 * @author XL
 * 
 */
public class Zip04 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// 需打包的文件夾
		String inputFileName = "c:\\tt2";
		try {
			zip(inputFileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void zip(String inputFileName) throws Exception {
		String zipFileName = "c:\\test.zip";// 打包后文件名字
		System.out.println(zipFileName);
		zip(zipFileName, new File(inputFileName));
	}

	public static void zip(String zipFileName, File inputFile) throws Exception {
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
				zipFileName));
		zip(out, inputFile, "");
		System.out.println("zip done");
		out.close();
	}

	public static void zip(ZipOutputStream out, File f, String base)
			throws Exception {
		if (f.isDirectory()) {
			File[] fl = f.listFiles();
			out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
			base = base.length() == 0 ? "" : base + "/";
			for (int i = 0; i < fl.length; i++) {
				zip(out, fl[i], base + fl[i].getName());
			}
		} else {
			out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
			FileInputStream in = new FileInputStream(f);
			int b;
			System.out.println(base);
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			in.close();
		}
	}
}
 

你可能感兴趣的:(Java基础技术)