java压缩zip文件夹错误_Java操作Zip压缩文件遇到的编码问题

标签:

1、遇到的问题:在for循环操作zip文件(文件名包含中文)的过程中,报错如下:

Exception in thread "main" java.lang.IllegalArgumentException: MALFORMED

at java.util.zip.ZipCoder.toString(ZipCoder.java:58)

at java.util.zip.ZipInputStream.readLOC(ZipInputStream.java:297)

at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:121)

at com.forestfood.FileUntils.done(FileUntils.java:224)

at com.forestfood.FileUntils.getActionZipFiles(FileUntils.java:196)

at com.forestfood.FileUntils.main(FileUntils.java:24)

2、查找原因:追查报错代码行至  ZipCoder.java:58

final class ZipCoder {

String toString(byte[] ba, int length) {

CharsetDecoder cd = decoder().reset();

int len = (int)(length * cd.maxCharsPerByte());

char[] ca = new char[len];

if (len == 0)

return new String(ca);

// UTF-8 only for now. Other ArrayDeocder only handles

// CodingErrorAction.REPLACE mode. ZipCoder uses

// REPORT mode.

if (isUTF8 && cd instanceof ArrayDecoder) {

int clen = ((ArrayDecoder)cd).decode(ba, 0, length, ca);

if (clen == -1)    // malformed

throw new IllegalArgumentException("MALFORMED");

return new String(ca, 0, clen);

}

可以发现,如果不指定编码的时候,默认是UTF-8,在解码的时候就会发生错误。

3、解决方法:在创建zip的时候,指定编码

FileInputStream fileInputStream = new FileInputStream(zipPath);

Charset gbk = Charset.forName("gbk");

ZipInputStream zin = new ZipInputStream(fileInputStream,gbk);

ZipEntry entry = zin.getNextEntry();

标签:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值