欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

解决java使用zip解压压缩包时出现java.lang.IllegalArgumentException: MALFORMED错误

程序员文章站 2022-05-15 12:37:14
...

今天在使用java zip解压压缩包时出现了java.lang.IllegalArgumentException: MALFORMED错误,查阅了资料,发现是压缩包文件的编码问题,zip源码里面都默认采用了UTF_8编码,遇到不是UTF_8编码的压缩包时就会报MALFORMED错误,MALFORMED的意思是畸形的,好比压缩包用了不同的编码导致无法解析。

解决:新建zip解压对象时,使用带编码类型的构造函数,编码使用GBK。代码如下:

//使用ZipInputStream
ZipInputStream zip = new ZipInputStream(multipartFile.getInputStream(), Charset.forName("GBK"));
//使用ZipFile
ZipFile zipFile = new ZipFile(new File("sourcePath"), Charset.forName("GBK"));

java zip相关类源代码片段如下:

/********* ZipInputStream *********/
     /**
     * Creates a new ZIP input stream.
     *
     * <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
     * decode the entry names.
     *
     * @param in the actual input stream
     */
    public ZipInputStream(InputStream in) {
        this(in, StandardCharsets.UTF_8);
    }

/********* ZipFile *********/ 
    /**
     * Opens a new <code>ZipFile</code> to read from the specified
     * <code>File</code> object in the specified mode.  The mode argument
     * must be either <tt>OPEN_READ</tt> or <tt>OPEN_READ | OPEN_DELETE</tt>.
     *
     * <p>First, if there is a security manager, its <code>checkRead</code>
     * method is called with the <code>name</code> argument as its argument to
     * ensure the read is allowed.
     *
     * <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
     * decode the entry names and comments
     *
     * @param file the ZIP file to be opened for reading
     * @param mode the mode in which the file is to be opened
     * @throws ZipException if a ZIP format error has occurred
     * @throws IOException if an I/O error has occurred
     * @throws SecurityException if a security manager exists and
     *         its <code>checkRead</code> method
     *         doesn't allow read access to the file,
     *         or its <code>checkDelete</code> method doesn't allow deleting
     *         the file when the <tt>OPEN_DELETE</tt> flag is set.
     * @throws IllegalArgumentException if the <tt>mode</tt> argument is invalid
     * @see SecurityManager#checkRead(java.lang.String)
     * @since 1.3
     */
    public ZipFile(File file, int mode) throws IOException {
        this(file, mode, StandardCharsets.UTF_8);
    }

    /**
     * Opens a ZIP file for reading given the specified File object.
     *
     * <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
     * decode the entry names and comments.
     *
     * @param file the ZIP file to be opened for reading
     * @throws ZipException if a ZIP format error has occurred
     * @throws IOException if an I/O error has occurred
     */
    public ZipFile(File file) throws ZipException, IOException {
        this(file, OPEN_READ);
    }
    

 

相关标签: 解压 zip