Home> Java> JavaBase> body text

java compression garbled code

angryTom
Release: 2019-11-15 11:50:16
Original
2241 people have browsed it

java compression garbled code

java compression garbled code

Usually using java to package files and generate compressed files, the problem of Chinese garbled content will appear , 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 libraryorg.apache .tools.zip.ZipOutputStreamandorg.apache.tools.zip.ZipEntryare included in ant.jar and can be downloaded and used directly.

There is no doubt that it is more convenient to choose the latter. org.apache.tools.zip.ZipOutputStream uses the encoding method of the project by default. In theory, utf-8 also supports Chinese. If it is still garbled,The solution can be solved by changing the setEncoding method to gbk.

The sample code is as follows:

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

php Chinese website, a large number of freeJava introductory tutorials, welcome to learn online!

The above is the detailed content of java compression garbled code. 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
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!