我有一个代码可以解压缩一个 zip 文件,但在解压缩一个压缩目录时失败 -
public static String unZipFile(String fileZip) throws IOException {
File destDir = new File(System.getProperty("user.dir"));
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
File newFile = newFile(destDir, zipEntry);
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
return destDir.toString();
}
public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
File destFile = new File(destinationDir, zipEntry.getName());
String destDirPath = destinationDir.getCanonicalPath();
String destFilePath = destFile.getCanonicalPath();
if (!destFilePath.startsWith(destDirPath + File.separator)) {
throw new IOException("Entry is outside of the target dir: " +
zipEntry.getName());
}
return destFile;
}
命令行发誓 -
`C:\Users\phil\Desktop>java -jar c:\Users\phil\Desktop\Archiver-1.0-
SNAPSHOT.jar c:\Users\phil\Desktop\dirCompressed.zip
Exception in thread "main" java.io.FileNotFoundException:
C:\Users\phil\Desktop\Text (Отказано в доступе)
at java.base/java.io.FileOutputStream.open0(Native Method)
at java.base/java.io.FileOutputStream.open(FileOutputStream.java:291)
at java.base/java.io.FileOutputStream.<init>
(FileOutputStream.java:234)
at java.base/java.io.FileOutputStream.<init>
(FileOutputStream.java:184)
at ZipArchiver.unZipFile(ZipArchiver.java:79)
at Main.main(Main.java:9)`
我究竟做错了什么?
您需要检查它是否是一个
zipEntry目录。在这种情况下,您不需要从存档中写入文件,而是创建一个新目录。英文版类似讨论: