我在使用Java解压缩ZIP文件时遇到问题。方法如下。
文件解压缩后文件结构正确,这意味着ZIP文件中的目录很好,但文件输出的长度为零。
我已经检查了ZIP文件,看看压缩是否正确,一切都正确。
如果有人看到我错过的东西......
public static void unzip ( File zipfile, File directory ) throws IOException {
ZipFile zip = new ZipFile ( zipfile );
Enumeration<? extends ZipEntry> entries = zip.entries ();
while ( entries.hasMoreElements () ) {
ZipEntry entry = entries.nextElement ();
File file = new File ( directory, entry.getName () );
if ( entry.isDirectory () ) {
file.mkdirs ();
}
else {
file.getParentFile ().mkdirs ();
ZipInputStream in = new ZipInputStream ( zip.getInputStream ( entry ) );
OutputStream out = new FileOutputStream ( file );
byte[] buffer = new byte[4096];
int readed = 0;
while ( ( readed = in.read ( buffer ) ) > 0 ) {
out.write ( buffer, 0, readed );
out.flush ();
}
out.close ();
in.close ();
}
}
zip.close ();
}
更多......显然方法 getInputStream(entry)返回零字节,不知道为什么。
答案 0 :(得分:2)
ZipFile已经解压缩条目的数据,也不需要使用ZipInputStream
。
而不是:
ZipInputStream in = new ZipInputStream ( zip.getInputStream ( entry ) );
使用:
InputStream in = zip.getInputStream ( entry );
ZipInputStream也可用于解压缩ZIP文件。你得到零长度流的原因是因为使用ZipInputStream你需要调用getNextEntry()来读取ZIP中的第一个文件。
答案 1 :(得分:-1)
以下代码有效:
package so;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
public class TestZip {
public static void main(String[] args) {
String path = "C:" + File.separator + "tmp" + File.separator;
String nom = "demo.zip";
File zipfile = new File(path + nom);
File directory = new File(path);
TestZip m = new TestZip();
try {
m.unzip(zipfile, directory);
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
public static void unzip ( File zipfile, File directory ) throws IOException {
System.out.println(zipfile.toString());
System.out.println(directory.toString());
ZipFile zip = new ZipFile ( zipfile );
System.out.println("1");
Enumeration<? extends ZipEntry> entries = zip.entries ();
System.out.println("2");
while ( entries.hasMoreElements () ) {
System.out.println("3");
ZipEntry entry = entries.nextElement ();
File file = new File ( directory, entry.getName () );
if ( entry.isDirectory () ) {
file.mkdirs ();
}
else {
file.getParentFile ().mkdirs ();
ZipInputStream in = new ZipInputStream ( zip.getInputStream ( entry ) );
OutputStream out = new FileOutputStream ( file );
byte[] buffer = new byte[4096];
int readed = 0;
while ( ( readed = in.read ( buffer ) ) > 0 ) {
out.write ( buffer, 0, readed );
out.flush ();
}
out.close ();
in.close ();
}
}
zip.close ();
}
}
所以我认为问题在于您传递的参数。使用“new File(complete_path + filename)”创建参数“zipfile”。如果您只是使用文件名创建它不起作用。