java zip字符编码,Java zip字符编码

I'm using the following method to compress a file into a zip file:

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();

}

}

}

My problem is that i have flat text files with the content N°TICKET for example, the zipped result gives some weired characters when uncompressed N° TICKET. Also characters such as é and à are not supported.

I guess it's due to the character encoding, but I don't know how to set it in my zip method to ISO-8859-1 ?

(I'm running on windows 7, java 6)

解决方案

You are using streams which write exactly the bytes that they are given. Writers interpret character data and convert it to the corresponding bytes and Readers do the opposite. Java (at least in version 6) doesn't provide an easy way to to mix and match operations on zipped data and for writing characters.

This way will work though. It is, however, a little clunky.

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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值