Home > Java > JavaBase > body text

Java compressed file garbled problem

Release: 2019-12-21 16:38:56
Original
2190 people have browsed it

Java compressed file garbled problem

Use java to package files to generate compressed files. There are two places where garbled characters will appear:

1. The Chinese garbled content problem: modify the source code of sun. Use the open source class libraries org.apache.tools.zip.ZipOutputStream and org.apache.tools.zip.ZipEntry. These two classes are available in ant.jar and can be downloaded and used.

2. The Chinese garbled problem of compressed file comments: zos.setComment("Chinese test"); Find the problem by using the setting encoding method (zos.setEncoding("gbk");) and test the encoding of the project The mode is gbk, and the default encoding is utf-8.

org.apache.tools.zip.ZipOutputStream uses the encoding method of the project by default, which can be solved by changing it to gbk through the setEncoding method.

java compressed file code:

package com.compress;  
  
import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;  
import java.io.DataInputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
  
import org.apache.tools.zip.ZipEntry;  
import org.apache.tools.zip.ZipOutputStream;  
  
public class CompressEncodingTest {  
  
    /** 
     * @param args 
     * @throws Exception 
     */  
    public static void main(String[] args) throws Exception {  
        File f = new File("中文测试.txt");  
        ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(  
                new FileOutputStream("zipTest.zip"), 1024));  
        zos.putNextEntry(new ZipEntry("中国人.txt"));  
        DataInputStream dis = new DataInputStream(new BufferedInputStream(  
                new FileInputStream(f)));  
        zos.putNextEntry(new ZipEntry(f.getName()));  
        int c;  
        while ((c = dis.read()) != -1) {  
            zos.write(c);  
        }  
  
        zos.setEncoding("gbk");  
        zos.setComment("中文测试");  
  
        zos.closeEntry();  
        zos.close();  
    }  
  
}
Copy after login

For more java knowledge, please pay attention to the java basic tutorial column.

The above is the detailed content of Java compressed file garbled problem. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!