Java操做Zip壓縮文件遇到的編碼問題

一、遇到的問題:在for循環操做zip文件(文件名包含中文)的過程當中,報錯以下:    java

     

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)

二、查找緣由:追查報錯代碼行至  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,在解碼的時候就會發生錯誤。spa

三、解決方法:在建立zip的時候,指定編碼rest

FileInputStream fileInputStream = new FileInputStream(zipPath);
Charset gbk = Charset.forName("gbk");
ZipInputStream zin = new ZipInputStream(fileInputStream,gbk);
ZipEntry entry = zin.getNextEntry();
相關文章
相關標籤/搜索