史上最简单解决ZipOutputStream压缩文件中文名乱码问题

来源:互联网 发布:软件测试工资水平 编辑:程序博客网 时间:2024/06/15 18:33

用关键字“ZipOutputStream 压缩 中文乱码问题”一大把,无非是两种方法:

第一种就是改JDK源码, 把ZipOutputStream拷贝出来,修改下编码

第二种就是用apache-ant

这两种方法详见http://blog.csdn.net/zhanghw0917/article/details/5628039


这里介绍一种最简单的办法,不用改源代码,也不用换apache-ant,上面这两种办法出现中文乱码的问题都是基于JDK6,但是在JDK7中已经解决了,只要把JDK版本升到7就可以。

从两个版本的源码比较就知道了:

JDK6u21的ZipOutputStream.java的源码片段:

/** * Creates a new ZIP output stream. *  * @param out * the actual output stream */public ZipOutputStream(OutputStream out) {super(out, new Deflater(Deflater.DEFAULT_COMPRESSION, true));usesDefaultDeflater = true;}/** * Sets the ZIP file comment. *  * @param comment * the comment string * @exception IllegalArgumentException * if the length of the specified ZIP file comment is greater * than 0xFFFF bytes */public void setComment(String comment) {if (comment != null && comment.length() > 0xffff / 3&& getUTF8Length(comment) > 0xffff) {throw new IllegalArgumentException("ZIP file comment too long.");}this.comment = comment;}


JDK7u65的ZipOutputStream.java的源码片段:

/**     * Creates a new ZIP output stream.     *     * <p>The UTF-8 {@link java.nio.charset.Charset charset} is used     * to encode the entry names and comments.     *     * @param out the actual output stream     */    public ZipOutputStream(OutputStream out) {        this(out, StandardCharsets.UTF_8);    }    /**     * Creates a new ZIP output stream.     *     * @param out the actual output stream     *     * @param charset the {@linkplain java.nio.charset.Charset charset}     *                to be used to encode the entry names and comments     *     * @since 1.7     */    public ZipOutputStream(OutputStream out, Charset charset) {        super(out, new Deflater(Deflater.DEFAULT_COMPRESSION, true));        if (charset == null)            throw new NullPointerException("charset is null");        this.zc = ZipCoder.get(charset);        usesDefaultDeflater = true;    }    /**     * Sets the ZIP file comment.     * @param comment the comment string     * @exception IllegalArgumentException if the length of the specified     *            ZIP file comment is greater than 0xFFFF bytes     */    public void setComment(String comment) {        if (comment != null) {            this.comment = zc.getBytes(comment);            if (this.comment.length > 0xffff)                throw new IllegalArgumentException("ZIP file comment too long.");        }    }


从JDK6版本中可以看出,只有一个带OutputStream参数的构造方法,并且没有传入字符集,而JDK7版本中的有两个构造方法,一个是带OutputStream和Charset的构造方法,另外一个就是重载,只有一个OutputStream,默认字符集UTF-8。


1 0
原创粉丝点击