我正在使用以下方法将文件压缩为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)
答案 0 :(得分:4)
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")
答案 1 :(得分:4)
您正在使用精确写入给定字节的流。编写者解释字符数据并将其转换为相应的字节,而读者则相反。 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();
答案 2 :(得分:0)
尝试使用org.apache.commons.compress.archivers.zip.ZipFile;不是java自己的库,所以你可以给出这样的编码:
import org.apache.commons.compress.archivers.zip.ZipFile;
ZipFile zipFile = new ZipFile(filepath,encoding);