gpt4 book ai didi

java - 如何在java中解压不是UTF8格式的文件

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:30:47 26 4
gpt4 key购买 nike

我有一个文件,例如测试.zip。如果我使用像 winrar 这样的 ZIP 工具,它很容易提取(将 test.zip 解压缩到 test.csv)。但是 test.csv 不是 UTF8 格式。我的问题是,当我使用 java 解压缩它时,它无法读取该文件。

ZipFile zf = new ZipFile("C:/test.zip");

抛出的异常表示打开该文件时发生错误。

在 Java 上 http://java.sun.com/developer/technicalArticles/Programming/compression/没有写关于数据格式的内容。也许整个 API 只是为 UTF8 格式的数据设计的。那么,如果我必须解压非UTF8格式的数据,如何解压呢?尤其是日文和中文字符占用更多的空间大小(UTF8 除外)。我还在 http://truezip.java.net/6/tutorial.html提到这个问题的地方。但是,我没有找到解决方法。有什么简单的方法可以解决这个问题吗?特别是从 JAVA 规范请求传递的 API。

最佳答案

JDK6 在 java.util.zip 实现中有一个错误,它不能处理非 USASCII 字符。我使用 Apache Commons commons-compress-1.0.jar 库来修复它。 JDK7 已修复 java.util.zip 实现。 http://docs.oracle.com/javase/7/docs/api/java/util/zip/ZipInputStream.html

import java.io.*;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.*;

public static int unzip(File inputZip, File outputFolder) throws IOException {
int count=0;
FileInputStream fis = null;
ZipArchiveInputStream zis = null;
FileOutputStream fos = null;
try {
byte[] buffer = new byte[8192];
fis = new FileInputStream(inputZip);
zis = new ZipArchiveInputStream(fis, "Cp1252", true); // this supports non-USACII names
ArchiveEntry entry;
while ((entry = zis.getNextEntry()) != null) {
File file = new File(outputFolder, entry.getName());
if (entry.isDirectory()) {
file.mkdirs();
} else {
count++;
file.getParentFile().mkdirs();
fos = new FileOutputStream(file);
int read;
while ((read = zis.read(buffer,0,buffer.length)) != -1)
fos.write(buffer,0,read);
fos.close();
fos=null;
}
}
} finally {
try { zis.close(); } catch (Exception e) { }
try { fis.close(); } catch (Exception e) { }
try { if (fos!=null) fos.close(); } catch (Exception e) { }
}
return count;
}

关于java - 如何在java中解压不是UTF8格式的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11734084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com