java解压zip乱码问题(2009-08-27 18:59:01)转载▼标签: 杂谈
在网上找了很多的资料,大概上有两种解决办法:
第一种是用java.util.zip,可是这种java给写死了编码格式指定为了UTF-8的,所以乱码问题是没办法处理的,看有些人说可以改src.zip里面的类ZipInputStream和ZipOutputStream来解决乱码问题,具体能不能解决就不知道了,本人也没有去测试(因为我不喜欢这种处理方式,感觉这是治标不治本的做法)。
第二种方法是用ant.jar带的org.apache.tools.zip,而且看了很多类似的文章说能够解决乱码
问题了,也许是自己没弄明白吧,把代码拷来测试的时候是能够正常的解
压缩了,可乱码问题还是有的,我开发环境编码是UTF-8的,一样的代码不知道他们乱码问题是怎么处理的,我还得多学习
学习,
花了很长的时间研究代码,后来改动了下结果乱码问题就解决了,可能是和我的编码格式有关吧,把我整理的代码放这方便以后可以在看看(都是在网上找的资料,呵呵不是本人写的)
package com.bjtxx.lms.server.tools;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tools.zip.ZipOutputStream;
public class ZipTest {
public static void zip(ZipOutputStream out, File f, String base, boolean first)
throws Exception {
if (first) {
if (f.isDirectory()) {
out.putNextEntry(new org.apache.tools.zip.ZipEntry("/"));
base = base + f.getName();
first = false;
} else
base = f.getName();
}
if (f.isDirectory()) {
File[] fl = f.listFiles();
base = base + "/";
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + fl[i].getName(), first);
}
} 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();
}
}
@SuppressWarnings("unchecked")
public static void unZipFileByOpache(org.apache.tools.zip.ZipFile zipFile,
String unZipRoot) throws Exception, IOException {
java.util.Enumeration e = zipFile.getEntries();
System.out.println(zipFile.getEncoding());
org.apache.tools.zip.ZipEntry zipEntry;
while (e.hasMoreElements()) {
zipEntry = (org.apache.tools.zip.ZipEntry) e.nextElement();
InputStream fis = zipFile.getInputStream(zipEntry);
if (zipEntry.isDirectory()) {
} else {
File file = new File(unZipRoot + File.separator + zipEntry.getName());
File parentFile = file.getParentFile();
parentFile.mkdirs();
FileOutputStream fos = new FileOutputStream(file);
byte[]
b = new byte[1024];
int len;
while ((len = fis.read(b, 0, b.length)) != -1) {
fos.write(b, 0, len);
}
fos.close();
fis.close();
}
}
}
public static void ZipFile(String zipFileName, String inputFileName)
throws Exception {
org.apache.tools.zip.ZipOutputStream out = new org.apache.tools.zip.ZipOutputStream(
new FileOutputStream(zipFileName));
out.setEncoding("gbk");//设置的和文件名字格式一样或开发环境编码设置一样的话就能正常显示了
File inputFile = new File(inputFileName);
zip(out, inputFile, "", true);
System.out.println("zip done");
out.close();
}
public static void unZipFile(String unZipFileName, String unZipPath)
throws Exception {
org.apache.tools.zip.ZipFile zipFile = new org.apache.tools.zip.ZipFile(
unZipFileName, "gbk");
unZipFileByOpache(zipFile, unZipPath);
System.out.println("u