Java compressed zip file Chinese messy code problem solution

  • 2020-04-01 03:25:19
  • OfStack

Generally, after using Java to package files to generate compressed files, the following two places will appear gargoyles:

1, the content of the Chinese garbled code problem, this problem many people on the Internet gave the solution, there are two main methods: one is to modify the source code of sun; Another is the use of open source libraries org. Apache. Tools. Zip. ZipOutputStream and org., apache) tools. Zip. ZipEntry,. These two kinds of ant in the jar, and can be downloaded directly used to, there is no doubt that it is more convenient to choose the latter

2. Zos. setComment(" Chinese test "); There is little information on the online solutions to this problem. Test classes created by projects on their own machines, without any problems, but the use of the company's projects has been messy code, by using the method of setting coding(zos.setencoding (" GBK ");) Finally, I found the problem. The code of the test project was GBK, and the default code of the company's project was utf-8. Therefore, the test project was ok and there was a problem in the company's project.

Org. Apache. Tools. Zip. Use ZipOutputStream default encoding of the project, in theory, utf-8 is support in Chinese, really think impassability, why still gibberish, GBK by setEncoding change can be solved

The sample code for the above problems 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 {
 
 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(" The 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();
 }
}

Related articles: