今天写一个解压缩文件的小程序,各种问题,于是各种百度,各种找书最终得以解决
zip文件解压缩问题:no current ZIP entry ::: MALFORMED
解压含有中文问题:
java.lang.IllegalArgumentException: MALFORMED
at java.util.zip.ZipCoder.toString(Unknown Source)
at java.util.zip.ZipFile.getZipEntry(Unknown Source)
at java.util.zip.ZipFile.access$900(Unknown Source)
at java.util.zip.ZipFile$1.nextElement(Unknown Source)
at java.util.zip.ZipFile$1.nextElement(Unknown Source)
at com.cn.zip.ZipFileTest.unZip(ZipFileTest.java:50)
at com.cn.zip.ZipFileTest.main(ZipFileTest.java:29)
解决方式:
//最后实践可以解决压缩中文的问题,不过支持JDK1.7及以上
ZipFile zip = new ZipFile(fileName,Charset.forName("gbk"));
压缩问题:
java.util.zip.ZipException: no current ZIP entry
at java.util.zip.ZipOutputStream.write(Unknown Source)
at com.cn.zip.ZipFileTest.zip(ZipFileTest.java:170)
at com.cn.zip.ZipFileTest.zip(ZipFileTest.java:161)
at com.cn.zip.ZipFileTest.zip(ZipFileTest.java:161)
at com.cn.zip.ZipFileTest.zip(ZipFileTest.java:128)
at com.cn.zip.ZipFileTest.main(ZipFileTest.java:30)
代码:
public static void zip(ZipOutputStream out, String basePath, File file) {
try {
if (file.isDirectory()) {// 如果是目录
File[] files = file.listFiles();
if (files.length == 0) {
// 将文件夹放入zip中
out.putNextEntry(new ZipEntry(basePath + "/"));
out.closeEntry();
// 关闭zip文件中之前打开的项
}
for (File data : files) {
zip(out, basePath + "/" + data.getName(), data);
}
} else {
FileInputStream in = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(in);
byte[] buf = new byte[1024];
//1 out.putNextEntry(new ZipEntry(basePath));// 将文件夹放入zip中
int bat;
while ((bat = bis.read(buf)) != -1) {
out.write(buf, 0, bat); // 将字节流写入当前zip目录
}
//2 out.closeEntry();// 关闭zip文件中之前打开的项
if (bis != null) {
bis.close();
}
if (in != null) {
in.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
解决:
最终加上注释1、2的地方便可以了。
其中在写入文件的时候当我用BufferedOutPutStream进行写入时写入进压缩包中图片有大小,可是大部分图片都打不开,正在找原因。。