Search code examples
javazipinputstreamzipinputstream

Extract a Single File From ZipInputStream


I have an ZipInputStream made from a byte array , I can iterate through the zipInputStream ZipEntrys but I cant find a method to get the data from the ZipEntry (ZipENtry.getExtras() is null on every entry) how would i go to extract all the files one by one each one to a specific location on my disk ?

        try {
        ZipInputStream zipInputStream = new ZipInputStream(zip.getBody().getInputStream());
        ZipEntry temp;
        while((temp = zipInputStream.getNextEntry()) != null){
            File outputFile = new File(temp.getName());
            try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
                System.out.println(temp.getName());
                
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

Solution

  • Inside the while loop you just need one line call to transfer the current entry to target file:

    Files.copy(zipInputStream, outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    

    This will copy the current entry contents but won't close zipInputStream, then your loop may continue to the next entry.