解析zip压缩文件内包含中文名称 ZipInputStream不能支持中文解决

使用java代码解压zip压缩文件时,文件或文件夹出现中文名称是报错

ZipInputStream默认使用UTF_8

// An highlighted block
/**
     * Creates a new ZIP input stream.
     *
     * 

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); }

ZipInputStream可以指定编码

// An highlighted block
/**
    /**
     * Creates a new ZIP input stream.
     *
     * @param in the actual input stream
     *
     * @param charset
     *        The {@linkplain java.nio.charset.Charset charset} to be
     *        used to decode the ZIP entry name (ignored if the
     *         language
     *        encoding bit of the ZIP entry's general purpose bit
     *        flag is set).
     *
     * @since 1.7
     */
    public ZipInputStream(InputStream in, Charset charset) {
        super(new PushbackInputStream(in, 512), new Inflater(true), 512);
        usesDefaultInflater = true;
        if(in == null) {
            throw new NullPointerException("in is null");
        }
        if (charset == null)
            throw new NullPointerException("charset is null");
        this.zc = ZipCoder.get(charset);
    }

将编码设置为GBK解决中文报错问题,解决方法仅供参考


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Zip {

    /**
     * 解压压缩文件
     * @param inputStream 压缩文件流
     * @param container
     * @throws IOException
     */
    public void unZip(InputStream inputStream, Map<String, byte[]> container) throws IOException {
        ZipInputStream zip = new ZipInputStream(inputStream, Charset.forName("GBK"));
        ZipEntry zipEntry = null;
        while ((zipEntry = zip.getNextEntry()) != null) {
            String fileName = zipEntry.getName();// 得到文件名称
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] byte_s = new byte[1024];
            int num = -1;
            while ((num = zip.read(byte_s, 0, byte_s.length)) > -1) {// 通过read方法来读取文件内容
                byteArrayOutputStream.write(byte_s, 0, num);
            }
            container.put(fileName, byteArrayOutputStream.toByteArray());
        }
    }

}


你可能感兴趣的:(解析zip压缩文件内包含中文名称 ZipInputStream不能支持中文解决)