Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create ZIP files using list of Input streams?

In my case I have to download images from the resources folder in my web app. Right now I am using the following code to download images through URL.

url = new URL(properties.getOesServerURL() + "//resources//WebFiles//images//" + imgPath);

filename = url.getFile();               

is = url.openStream();
os = new FileOutputStream(sClientPhysicalPath + "//resources//WebFiles//images//" + imgPath);

b = new byte[2048];

while ((length = is.read(b)) != -1) {
    os.write(b, 0, length);
}

But I want a single operation to read all images at once and create a zip file for this. I don't know so much about the use of sequence input streams and zip input streams so if it is possible through these, please let me know.

like image 563
Amit Singh Avatar asked Aug 24 '13 09:08

Amit Singh


1 Answers

The only way I can see you being able to do this is something like the following:

try {

    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream("C:/archive.zip"));

    //GetImgURLs() is however you get your image URLs

    for(URL imgURL : GetImgURLs()) {
        is = imgURL.openStream();
        zip.putNextEntry(new ZipEntry(imgURL.getFile()));
        int length;

        byte[] b = new byte[2048];

        while((length = is.read(b)) > 0) {
            zip.write(b, 0, length);
        }
        zip.closeEntry();
        is.close();
    }
    zip.close();
}

Ref: ZipOutputStream Example

like image 63
Shane Haw Avatar answered Oct 26 '22 02:10

Shane Haw