9

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.

Griffin
  • 13,184
  • 4
  • 29
  • 43
Avyaan
  • 1,285
  • 6
  • 20
  • 47
  • so are you asking how to download all images in //resources//WebFiles//images// and zip them into one zip file? How does imgPath get assigned? – Shane Haw Aug 24 '13 at 10:53
  • I already have imgPath.In my case i have list of imagepath that is located at //resources//WebFiles//images.I have to download all these images through URL at once. – Avyaan Aug 24 '13 at 11:00
  • 1
    Couldn't you just a ZipOuputStream http://docs.oracle.com/javase/6/docs/api/java/util/zip/ZipOutputStream.html and do something like what is done here http://examples.javacodegeeks.com/core-java/util/zip/create-zip-file-from-multiple-files-with-zipoutputstream/ by looping through each image? – Shane Haw Aug 24 '13 at 11:07
  • thanx for your efforts,but i have already gone throgh that example.it is useful upto 70%.here they have used the physical path of the file but in my case i dont have aphysical path. i have rendered image on broser only. – Avyaan Aug 24 '13 at 11:34

2 Answers2

8

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

fujy
  • 5,168
  • 5
  • 31
  • 50
Shane Haw
  • 723
  • 9
  • 22
2

The url should return zip file. Else you have to take one by one and create a zip using your program

Crickcoder
  • 2,135
  • 4
  • 22
  • 36
  • may you explain it in some more details – Avyaan Aug 24 '13 at 10:22
  • You can make a list of Files. Then, create a zip file. Loop over the list and write each file to that zip. You can refer to this for creating zipfile. http://stackoverflow.com/questions/1091788/how-to-create-a-zip-file-in-java – Crickcoder Aug 24 '13 at 23:27