论坛首页 Web前端技术论坛

java用Ant.jar的zip写文件解决文件名中文问题(转)

浏览 1609 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-01-09  

 

package ejbModule.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

/**
 * 文件压缩(支持中文文件名)
 * 
 * @author gaoyusi
 * 
 */
public class FileHelper {

	/**
	 * 中文条件下文件(夹)压缩
	 * 
	 * @throws IOException
	 */
	public static void zipCompress(String src, String des) throws IOException {
		ZipOutputStream out = null;
		try {
			CheckedOutputStream cusm = new CheckedOutputStream(
					new FileOutputStream(des), new Adler32());
			out = new ZipOutputStream(new BufferedOutputStream(cusm));

			fileZip(new File(src), out, "");
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	private static void fileZip(File file, ZipOutputStream out, String base)
			throws IOException {
		if (file.isFile()) {
			if (base.length() > 0) {
				out.putNextEntry(new ZipEntry(base));
			} else {
				out.putNextEntry(new ZipEntry(file.getName()));
			}

			BufferedReader in = new BufferedReader(new InputStreamReader(
					new FileInputStream(file), "ISO8859_1"));

			int c;
			while ((c = in.read()) != -1) {
				out.write(c);
			}
			in.close();

		} else if (file.isDirectory()) {
			File[] subFiles = file.listFiles();

			out.putNextEntry(new ZipEntry(base + File.separator));
			base = base.length() != 0 ? base + File.separator : "";

			for (File subFile : subFiles) {
				fileZip(subFile, out, base + subFile.getName());
			}
		}

	}

	public static void main(String[] args) throws IOException {
		FileHelper.zipCompress("d:\\test","d:\\test1.zip");
	}
}

 

注意引入Ant.jar.

 

论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics