Usually, after using Java to package files and generate compressed files, garbled characters will appear in the following two places:
1. The problem of Chinese garbled content. Many people on the Internet have given solutions to this problem. There are two main methods: one is to modify the source code of sun; the other is to use the open source class library org.apache.tools.zip.ZipOutputStream and org.apache.tools.zip.ZipEntry, these two classes are included in ant.jar and can be downloaded and used directly. There is no doubt that it is more convenient to choose the latter.
2. The problem of Chinese garbled characters in compressed file comments: zos.setComment("Chinese test"); there is less information on the solution to this problem online. There were no problems with the test classes created by the project on my own machine, but when used in the company's projects, garbled characters kept appearing. By using the method of setting the encoding (zos.setEncoding("gbk");), I finally found the problem in the test project. The encoding method is gbk, and the default encoding of the company's project is utf-8, so there is no problem with the test project but there is a problem with the company's project.
org.apache.tools.zip.ZipOutputStream uses the encoding method of the project by default. Theoretically speaking, utf-8 also supports Chinese. I really can’t figure out why it is still garbled. You can solve it by changing the setEncoding method to gbk.
The sample code for the above problem is as follows:
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("Chinese test. txt"); ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream( new FileOutputStream("zipTest.zip"), 1024)); zos.putNextEntry(new ZipEntry("Chinese.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("Chinese Test"); zos.closeEntry(); zos.close() ; }}