Help modify the code. It unpacks Zip perfectly, but I need it to unpack files into a folder with the same name as the archive name.

private boolean unpackZip(String path, String zipname) { InputStream is; ZipInputStream zis; try { is = new FileInputStream(path + zipname); zis = new ZipInputStream(new BufferedInputStream(is)); ZipEntry ze; while((ze = zis.getNextEntry()) != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int count; String filename = ze.getName(); FileOutputStream fout = new FileOutputStream(path + filename); // reading and writing while((count = zis.read(buffer)) != -1) { baos.write(buffer, 0, count); byte[] bytes = baos.toByteArray(); fout.write(bytes); baos.reset(); } fout.close(); zis.closeEntry(); } zis.close(); } catch(IOException e) { e.printStackTrace(); return false; } return true; } 
  • That is, it is not clear to you how to get the name of the archive, without the extension, how to create a folder with that name or how to unpack the zip into it? - Kromster
  • one
    Semyon Semyonitch! So what's the problem? Make the task decomposition and search in Google. 1. Select the name of the archive from the archive - it is already in the variable filename 2. Check if the corresponding folder path+filename exists Use java.nio.file.Files and Files.exists(path) 3. If it does not exist, create the folder new File("C:\\Directory1").mkdir(); from java.io.File 4. Go to the folder you created. Or add its name to the path variable. 5. Unpack. PROFIT. - gecube

1 answer 1

Here is a while loop rewritten:

 while((ze = zis.getNextEntry()) != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int count; String filename = ze.getName(); if(ze.isDirectory()) { File directPath = new File(path + zipname.substring(0,zipname.length()-4) + "\\" + filename); directPath.mkdirs(); } else { File directPath = new File(path + zipname.substring(0,zipname.length()-4) + "\\"); directPath.mkdir(); FileOutputStream fout = new FileOutputStream(path + zipname.substring(0,zipname.length()-4) + "\\" + filename); // reading and writing while((count = zis.read(buffer)) != -1) { baos.write(buffer, 0, count); byte[] bytes = baos.toByteArray(); fout.write(bytes); baos.reset(); } fout.close(); zis.closeEntry(); } } 
  • zipname.substring (0, zipname.length () - 4) - without this, it will try to write to the archive, but it is better to take to the last point, via lastIndexOf. - Maxim Drobyshev
  • @AlexTortov, not at all) - Maxim Drobyshev