开发的时候一开始用的java.util.zip.ZipFile,这个好像是不支持中文,中文名字的文件加压出来都是????.json这样的。
网上都说Apache的包邮这个功能,就是这个包太大了。后来发现这个东西http://download.csdn.net/detail/huyongl1989/9120755。
使用方法如下
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
/**
* 解决解压中文乱码
* Created by sunlinlin on 2017/3/14.
*/
public class ZipUtil2 {
public static void upZipFile(File zipFile, String folderPath) throws IOException {
OutputStream os = null;
InputStream is = null;
ZipFile zf = null;
try {
zf = new ZipFile(zipFile,"UTF-8");//这里可以指定编码。可以试试GBK和UTF-8,我自己用GBK还是有乱码,只是从一串问号变成了一串乱码。
String directoryPath = "";
directoryPath = folderPath;
Enumeration entryEnum = zf.getEntries();
if (null != entryEnum) {
ZipEntry zipEntry = null;
while (entryEnum.hasMoreElements()) {
zipEntry = (ZipEntry) entryEnum.nextElement();
if (zipEntry.isDirectory()) { //不处理文件夹
directoryPath = directoryPath + File.separator
+ zipEntry.getName();
System.out.println(directoryPath);
continue;
}
if (zipEntry.getSize() > 0) {
File targetFile = new File(directoryPath+ File.separator + zipEntry.getName());
if (!targetFile.exists()) { //如果不存在就创建
File fileParentDir = targetFile.getParentFile();
if (!fileParentDir.exists()) {
fileParentDir.mkdirs();
}
targetFile.createNewFile();
}
//Log.i(TAG, new String(zipEntry.getName().getBytes(),"UTF-8"));
os = new BufferedOutputStream(new FileOutputStream(targetFile));
is = zf.getInputStream(zipEntry);
byte[] buffer = new byte[4096];
int readLen = 0;
while ((readLen = is.read(buffer, 0, 1024)) >= 0) {
os.write(buffer, 0, readLen);
}
os.flush();
os.close();
}
}
}
} catch (IOException ex) {
throw ex;
} finally {
if (null != zf) {
zf = null;
}
if (null != is) {
is.close();
}
if (null != os) {
os.close();
}
}
}
}