昨天接到了一个解压zip文件的任务,所以今天在做任务之前,便写demo试了一下,
部分思路参考自:这里
贴上代码:
public void Decompressing2() throws IOException {
String path = "E:\\zipTest";
ZipEntry zipEntry = null;
try (
// ZipInputStream读取压缩文件
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(path + "\\toefl.zip"),Charset.forName("GBK"));
// 写入到缓冲流中
BufferedInputStream bufferedInputStream = new BufferedInputStream(zipInputStream);){
File fileOut = null;
// 读取压缩文件中的一个文件
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
// 若当前zipEntry是一个文件夹
if (zipEntry.isDirectory()) {
fileOut = new File(path + "//" +zipEntry.getName());
// 在指定路径下创建文件夹
if (!fileOut.exists()) {
fileOut.mkdirs();
}
//若是文件
} else {
// 原文件名与指定路径创建File对象(解压后文件的对象)
fileOut = new File(path, zipEntry.getName());
try(
FileOutputStream fileOutputStream = new FileOutputStream(fileOut);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);){
//将文件写入到指定file中
int b = 0;
while ((b = bufferedInputStream.read()) != -1) {
bufferedOutputStream.write(b);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
在测试中发现,若压缩包中包含汉字会跑出异常!
查看源码发现:ZipInputStream对象有两个构造方法
发现其默认构造方法的CharSet对utf8格式:StandardCharsets.UTF_8
所以用ISO-8859-1试了一下
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(path + "/tpo40.zip"),StandardCharsets.ISO_8859_1);
结果如下:
打开解压后的文件:
解压后文件很正常(没有中文字符),但是文件夹名字乱码
后打算用GBK试一下:
查看StandardCharsets源码:
并没有GBK这个常量,但是 其成员的声明方法是:Charset.forName(“xxxx”)的方式。
所以采用如下方式创建ZipInputStream对象:
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(path + "\\toefl.zip"),Charset.forName("GBK"));
解压后OK,一切正常。
希望对大家有所帮助!!