我正在尝试从zip解压缩特定文件。我首先得到一个ZipInputStream
:
ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(filePath)));
好吧,这有效!现在我要提取两个文件,分别称为F1和F2,所以我称
extractFileFromZip(zipIn, Path + "F1", "F1")
extractFileFromZip(zipIn, Path + "F2", "F2")
public static boolean extractFileFromZip(ZipInputStream inZip, String file, String name) throws Exception {
byte data[] = new byte[BUFFER_SIZE];
boolean found = false;
ZipEntry ze;
while((ze = inZip.getNextEntry()) != null) {
if(ze.getName().equals(name)) {
found = true;
// delete old file first
File oldFile = new File(file);
if(oldFile.exists()) {
if(!oldFile.delete()) {
throw new Exception("Could not delete " + file);
}
}
FileOutputStream outFile = new FileOutputStream(file);
int count = 0;
while((count = inZip.read(data)) != -1) {
outFile.write(data, 0, count);
}
outFile.close();
//inZip.closeEntry();
}
}
return true;
}
现在问题出在
inZip.getNextEntry()
上。对于F1,它将正确循环浏览所有文件,然后提供null
。但是对于F2,它只会给出null
。为什么会这样?
最佳答案
您正在扫描整个流,将其消耗掉。当您第二次尝试执行此操作时,流已结束,因此将不执行任何操作。
另外,如果只需要压缩文件的一小部分,则流式传输zip文件中的所有字节的速度很慢。
请改用ZipFile
,因为它允许随机访问zip条目,因此速度更快,并且允许以随机顺序读取条目。
注意:以下代码已更改为使用Java 7+功能来更好地处理错误,例如try-with-resources和NIO.2。
ZipFile zipFile = new ZipFile(filePath);
extractFileFromZip(zipFile, path + "F1", "F1");
extractFileFromZip(zipFile, path + "F2", "F2");
public static boolean extractFileFromZip(ZipFile zipFile, String file, String name) throws IOException {
ZipEntry ze = zipFile.getEntry(name);
if (ze == null)
return false;
Path path = Paths.get(file);
Files.deleteIfExists(path);
try (InputStream in = zipFile.getInputStream(ze)) {
Files.copy(in, path);
}
return true;
}
或者,仅流一次,然后在
while
循环中检查两个名称。Map<String, String> nameMap = new HashMap<>();
nameMap.put("F1", path + "F1");
nameMap.put("F2", path + "F2");
extractFilesFromZip(filePath, nameMap);
public static void extractFilesFromZip(String filePath, Map<String, String> nameMap) throws IOException {
try (ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(filePath)))) {
for (ZipEntry ze; (ze = zipIn.getNextEntry()) != null; ) {
String file = nameMap.get(ze.getName());
if (file != null) {
Path path = Paths.get(file);
Files.deleteIfExists(path);
Files.copy(zipIn, path);
}
}
}
}