Home  >  Article  >  Java  >  Introduction to the causes and solutions of Java zip compression garbled characters

Introduction to the causes and solutions of Java zip compression garbled characters

尚
Original
2019-12-02 13:20:033383browse

Introduction to the causes and solutions of Java zip compression garbled characters

Causes and solutions to java zip compression garbled characters: (Recommended: java video tutorial)

Running environment

Jdk 1.5, win 7 Chinese version

There are zip compression related APIs in JDK1.5, under the java.util.zip package. Under normal circumstances, use the API that comes with the JDK to compress the directory (file) into a zip package. The steps are as follows:

ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file));
Out.putNextEntry(new ZipEntry(entryName));
//If entry is directory
//above codes are enough
//else if entry is file
//then the codes below is needed
FileInputStream in = new FileInputStream(infile);
byte[] bs = newbyte[1024];
int b = 0;
while((b = in.read(bs)) != -1) {
zos.write(bs, 0, b);
}
in.close();

If the directory name or file name to be packaged contains Chinese characters, the names of these directories or files Garbled characters will appear. The reason is that in the API that comes with the JDK, when writing ZipEntry, the default encoding used is UTF8 (it seems that there is only this one, and there is no way to change it. It is said that Java7 has improved), and win7 operation The Chinese version of the system uses GBK encoding when processing zip files. The encoding and decoding processes are different, causing the packaged files to be garbled in the Chinese version of win7.

The solution that can be adopted is to use a third-party API to implement zip compression to solve the problem of Chinese garbled characters. The following is the implementation of zip compression using apache's compress. The required jar package is commons-compress-1.2.jar

ArchiveOutputStream os = new ArchiveStreamFactory()
              .createArchiveOutputStream(ArchiveStreamFactory.ZIP, out);
if(os instanceof ZipArchiveOutputStream) {
((ZipArchiveOutputStream) os).setEncoding("GBK");
}
//...some code omitted
os.putArchiveEntry(new ZipArchiveEntry(path+"/"+file.getName()));
IOUtils.copy(new FileInputStream(file), os);
os.closeArchiveEntry();

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

The above is the detailed content of Introduction to the causes and solutions of Java zip compression garbled characters. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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