How to unzip a folder in a Java archive

There is a code that unpacks ALL folders starting from the root (in the archive), and I need to do 1 directory below, if you use this code, it creates a file folder that does not exist. In this example, there is an input archive of update.zip, it contains the only folder in the root directory,which complicates everything.As far as I understand, this code simply iterates through all the files in the archive and writes them in the same order.

File mods = new File("C:\\Users\\User\\AppData\\Roaming\\.minecraft\\");
    String[] files = mods.list((folder, name) -> name.endsWith(".jar"));
    try(ZipInputStream zin = new ZipInputStream(new FileInputStream("C:\\Users\\User\\AppData\\Roaming\\.minecraft\\обнова\\update.zip")))
    {
        ZipEntry entry;
        String name;
        long size;



        while((entry=zin.getNextEntry())!=null){

            name = entry.getName(); // получим название файла
            size=entry.getSize();  // получим его размер в байтах
            System.out.printf("File name: %s \t File size: %d \n", name, size);

            // распаковка
            boolean exist = false;
            for ( String fileName : files ) {
                if(name.equals(fileName)){
                    exist = true;

                }
            }
            if(!exist){
                System.out.println(name);
                FileOutputStream fout = new FileOutputStream("C:\\Users\\User\\AppData\\Roaming\\.minecraft\\" + name);
                for (int c = zin.read(); c != -1; c = zin.read()) {
                    fout.write(c);  //ЗАПИСЬ ФАЙЛА ИЗ АРХИВА

                }
                fout.flush();
                zin.closeEntry();
                fout.close();
                System.out.println("запись");
                exist = false;

            }




        }

    }
 0
Author: Алёша Авилов, 2020-04-21

1 answers

You can try something like this:

String source = "folder/source.zip";
String destination = "folder/source/";   

try {
    ZipFile zipFile = new ZipFile(source);
    zipFile.extractAll(destination);
} catch (ZipException e) {
    e.printStackTrace();
}

If the files you want to unzip have a password, you can try this method:

String source = "folder/source.zip";
String destination = "folder/source/";
String password = "password";

try {
    ZipFile zipFile = new ZipFile(source);
    if (zipFile.isEncrypted()) {
        zipFile.setPassword(password);
    }
    zipFile.extractAll(destination);
} catch (ZipException e) {
    e.printStackTrace();
}

I hope this helps you

 0
Author: Sergei Buvaka, 2020-04-22 07:38:27