Retrieve a compressed file from a ZIP file





This Java tip illustrates a method of retrieving a compressed file from a ZIP file.
This example reads a ZIP file and decompresses the first entry. Developer may modify the code according to their needs.

public class Decrypt {
    public void decrypt() {
        try {
            //Open the ZIP file
            String sourcefile = "source.zip";
            ZipInputStream in = new ZipInputStream(new FileInputStream(sourcefile));
          
            //Get the first entry
            ZipEntry entry = in .getNextEntry();
          
            //Open the output file
            String targetfile = "target";
            OutputStream out = new FileOutputStream(targetfile);
          
            //Target bytes from the ZIP file to the output file
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buff)) > 0) {
                out.write(buf, 0, len);
            }
          
            //Close the streams
            out.close();
            in.close();
        } catch (IOException e) {
        }
    }
}

The above code shows an implementation of a decryption process using Java's ZipInputStream and FileOutputStream classes. Here's how the code works:

1. The code creates a ZipInputStream object by passing in a FileInputStream of the source zip file.

2. It then uses the getNextEntry method to get the first entry in the zip file.

3. It creates an OutputStream object using a FileOutputStream of the target file where the decrypted data will be written.

4. The code then reads the data from the zip file into a buffer using the read method of the ZipInputStream object.

5. The read data is then written to the output file using the write method of the OutputStream object.

6. This process continues until all data has been read and written to the output file.

7. Finally, the code closes the input and output streams.



Previous Post Next Post