我对使用 Java 处理 zip 文件完全陌生, 我遇到了一个奇怪的情况。
这是我用来解压的方法:
public void unzip(File zipFile, File rootDir) throws IOException
{
ZipFile zip = new ZipFile(zipFile);
Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();
while(entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
java.io.File f = new java.io.File(rootDir, entry.getName());
if (entry.isDirectory()) { // if its a directory, create it
continue;
}
if (!f.exists()) {
f.getParentFile().mkdirs();
f.createNewFile();
}
/*BufferedInputStream bis = new BufferedInputStream(zip.getInputStream(entry)); // get the input stream
BufferedOutputStream bos = new BufferedOutputStream(new java.io.FileOutputStream(f));
while (bis.available() > 0) { // write contents of 'is' to 'fos'
bos.write(bis.read());
}
bos.close();
bis.close();*/
InputStream is = zip.getInputStream(entry);
OutputStream os = new java.io.FileOutputStream(f);
byte[] buf = new byte[4096];
int r ;
while ((r = is.read(buf)) != -1) {
os.write(buf, 0, r);
}
os.close();
is.close();
}
}
但是,抛出了一个 IOException 并且消息是:
信息 |虚拟机 1 | 2012/11/30 01:58:05 | java.util.zip.ZipException: 打开 zip 文件时出错
信息 |虚拟机 1 | 2012/11/30 01:58:05 |在 java.util.zip.ZipFile.open( native 方法)
信息 |虚拟机 1 | 2012/11/30 01:58:05 |在 java.util.zip.ZipFile.(ZipFile.java:127)
信息 |虚拟机 1 | 2012/11/30 01:58:05 |在 java.util.zip.ZipFile.(ZipFile.java:143)
谁能帮我解决这个问题?
非常感谢。
更新:
我正在使用 Linux 作为测试环境。 解压目录权限为drwxr-xr-x –
更新 02:
通过采纳@heikkim 的建议,
我刚刚尝试在 linux 中使用 unzip command,尝试手动解压缩我的文件。我收到以下消息:
存档:TMA_Template.zip 警告:zipfile 注释被截断 警告 [TMA_Template.zip]:zip 文件声称是多部分存档的最后一个磁盘; 无论如何都试图处理,假设所有部分都已连接 按顺序在一起。期待“错误”和警告......真正的多部分支持 尚不存在(即将推出)。 错误 [TMA_Template.zip]:压缩文件中缺少 6366880279 个字节 (无论如何尝试处理) 错误 [TMA_Template.zip]:尝试在 zip 文件开头之前查找 (请检查您是否已在 适当的 BINARY 模式并且您已正确编译 UnZip)
最佳答案
你能试试这个方法吗:
private void unzip() throws IOException {
int BUFFER = 2048;
BufferedOutputStream dest = null;
BufferedInputStream is = null;
ZipEntry entry;
ZipFile zipfile = new ZipFile("latest.zip");
Enumeration e = zipfile.entries();
(new File(root)).mkdir();
while (e.hasMoreElements()) {
entry = (ZipEntry) e.nextElement();
//outText.setText(outText.getText() + "\nExtracting: " + entry);
if (entry.isDirectory()) {
(new File(root + entry.getName())).mkdir();
} else {
(new File(root + entry.getName())).createNewFile();
is = new BufferedInputStream(zipfile.getInputStream(entry));
int count;
byte data[] = new byte[BUFFER];
FileOutputStream fos = new FileOutputStream(root + entry.getName());
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
is.close();
}
}
}
关于java - 在 Java 中解压缩文件时出现 ZipException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13642453/