Есть ли способ распаковать ZIP-файл с различными подпапками в Java без установки дополнительных плагинов.
Например, я хотел бы распаковать файл https://services.gradle.org/distributions/gradle-6.4.1-bin.zip с этим кодом:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class unzipfile {
private static void unzip(String zipFilePath, String zipFileName, String destDir) {
System.out.print("Extracting " + zipFileName + "...");
File dir = new File(destDir);
// create output directory if it doesn't exist
if(!dir.exists()) dir.mkdirs();
FileInputStream fis;
//buffer for read and write data to file
byte[] buffer = new byte[1024];
try {
fis = new FileInputStream(zipFilePath);
try (ZipInputStream zis = new ZipInputStream(fis)) {
ZipEntry ze = zis.getNextEntry();
while(ze != null){
String fileName = ze.getName();
File newFile = new File(destDir + File.separator + fileName);
//create directories for sub directories in zip
new File(newFile.getParent()).mkdirs();
try (FileOutputStream fos = new FileOutputStream(newFile)) {
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
//close this ZipEntry
ze = zis.getNextEntry();
}
}
fis.close();
System.out.println(" Done!");
} catch (IOException e) {
System.out.println(" Error while extracting " + zipFileName);
Logger.getLogger(unzipfile.class.getName()).log(Level.SEVERE, null, e);
}
}
public static void main(String[] args) {
try{
unzip(args[0], args[1], args[2]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("No valid arguments specified. Usage:\n");
System.out.println("\'java unzipfile [ZIP file path with file name] [file name only] [target directory]\'");
System.exit(1);
}
}
}
Я запускаю:
java unzipfile path\to\file\gradle-6.4.1-bin.zip gradle-6.4.1-bin.zip .
Но когда я запускаю полное приложение, он дает мне сообщение:
Extracting gradle-6.4.1-bin.zip... Error while extracting gradle-6.4.1-bin.zip
may. 27, 2020 5:44:37 P.áM. unzipfile unzip
SEVERE: null
java.io.FileNotFoundException: .\gradle-6.4.1\README (El sistema no puede encontrar la ruta especificada)
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 unzipfile.unzip(unzipfile.java:29)
at unzipfile.main(unzipfile.java:50)
Спасибо на ваше время.