Java zip字符编码

Maj*_*ssi 4 java zip encoding

我正在使用以下方法将文件压缩为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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我的文本文件带有内容N°TICKET,例如,压缩结果在未压缩时会给出一些奇怪的字符N° TICKET。还不支持诸如é和的字符à

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

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

Dun*_*nes 5

您正在使用的流将精确地写入给定的字节。写入器解释字符数据并将其转换为相应的字节,而读取器则相反。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();
Run Code Online (Sandbox Code Playgroud)