Search code examples
javasoap-client

called a soap web service which returns a zip file as an attachment. How to unzip it in memory?


I have seen posts about how to unzip files using Java, where the zip file is located somewhere on disk. In my case it's different.

I have code which calls a soap web service. The service response includes an attachment which is a zip file. I have been able to get the attachment. here is part of the code:

 Iterator<?> i = soapResponse.getAttachments();
 Object obj = null;
 AttachmentPart att = (AttachmentPart) i.next();

So, I have the zip file as a type "AttachmentPart" however I could also do:

byte[] arr1 = att.getRawContentBytes();

which would give me the array of bytes containing the zip file.

I could also do

Object obj = att.getContent()

So, I can get the zip files in different formats/types. The zip files contains two .csv files and I have to do different stuff to those files. To make my question simpler, all I am looking to do for now is to get the two .csv files and print its content to the console.

I want to do everything in memory. I don't want to put the content of the zip files on disk.

How can I unzip the attachment and print the content?


Solution

  • If you grab the att.getRawContent() from the AttachmentPart object, you can pass it to the built in ZipInputStream to read the contents of the zip file. You can then write the bytes read from the ZipInputStream directly to System.out to view the contents on the console.

    Below is an example that should read the zip contents and then write the entry name followed by the entry contents to standard out, assuming you pass it the AttachmentPart that contains the zip file. It will also filter out any entries that are directories so that they are not printed.

    public static void printAttachmentPartZip(AttachmentPart att) throws IOException, SOAPException {
        try (ZipInputStream zis = new ZipInputStream(att.getRawContent())) {
            byte[] buffer = new byte[1024];
            for (ZipEntry zipEntry = zis.getNextEntry(); zipEntry != null; zipEntry = zis.getNextEntry()) {
                if (zipEntry.isDirectory()) {
                    continue;
                }
                System.out.println(zipEntry.getName());
                for (int len = zis.read(buffer); len > 0; len = zis.read(buffer)) {
                    System.out.write(buffer, 0, len);
                }
            }
        }
    }