自学内容网 自学内容网

使用Java自带ZipInputStream解析zip压缩文件内包含中文名称 ZipInputStream不能支持中文解决

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

!!!ZipInputStream默认使用UTF_8,这样遇到中文文件时,会出现乱码报错为

IllegalArgumentException

只需要将编码转换为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());
        }
    }

}


原文地址:https://blog.csdn.net/weixin_71126140/article/details/137860709

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!