Java zip字符编码

我正在使用以下方法将文件压缩为zip文件:

import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public static void doZip(final File inputfis, final File outputfis) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; final CRC32 crc = new CRC32(); crc.reset(); try { fis = new FileInputStream(inputfis); fos = new FileOutputStream(outputfis); final ZipOutputStream zos = new ZipOutputStream(fos); zos.setLevel(6); final ZipEntry ze = new ZipEntry(inputfis.getName()); zos.putNextEntry(ze); final int BUFSIZ = 8192; final byte inbuf[] = new byte[BUFSIZ]; int n; while ((n = fis.read(inbuf)) != -1) { zos.write(inbuf, 0, n); crc.update(inbuf); } ze.setCrc(crc.getValue()); zos.finish(); zos.close(); } catch (final IOException e) { throw e; } finally { if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } } } 

我的问题是我有平面文本文件,例如内容为N°TICKET ,拉链结果在未压缩的N° TICKET时给出一些我们的字符。 此外,不支持éà等字符。

我想这是由于字符编码,但我不知道如何在我的zip方法中将其设置为ISO-8859-1

(我在Windows 7上运行,java 6)

您正在使用精确写入它们所给出的字节的流。 编写者解释字符数据并将其转换为相应的字节,而读者则相反。 Java(至少在版本6中)没有提供一种简单的方法来混合和匹配压缩数据和写字符的操作。

这种方式可行。 然而,它有点笨重。

 File inputFile = new File("utf-8-data.txt"); File outputFile = new File("latin-1-data.zip"); ZipEntry entry = new ZipEntry("latin-1-data.txt"); BufferedReader reader = new BufferedReader(new FileReader(inputFile)); ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(outputFile)); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(zipStream, Charset.forName("ISO-8859-1")) ); zipStream.putNextEntry(entry); // this is the important part: // all character data is written via the writer and not the zip output stream String line = null; while ((line = reader.readLine()) != null) { writer.append(line).append('\n'); } writer.flush(); // i've used a buffered writer, so make sure to flush to the // underlying zip output stream zipStream.closeEntry(); zipStream.finish(); reader.close(); writer.close(); 

Afaik这在Java 6中不可用。

但我相信http://commons.apache.org/compress/可以提供解决方案。

切换到Java 7提供了一个新的构造函数,该编译器作为附加参数进行编码。

https://blogs.oracle.com/xuemingshen/entry/non_utf_8_encoding_in

 zipStream = new ZipInputStream( new BufferedInputStream(new FileInputStream(archiveFile), BUFFER_SIZE), Charset.forName("ISO-8859-1") 

尝试使用org.apache.commons.compress.archivers.zip.ZipFile; 不是java自己的库,所以你可以给出这样的编码:

import org.apache.commons.compress.archivers.zip.ZipFile;

ZipFile zipFile = new ZipFile(filepath,encoding);