使用java在zip中下载图像

时间:2016-09-01 10:27:18

标签: java image

我正在尝试以zip格式下载图片,但是当我尝试运行以下代码时,它会说"压缩文件夹无效"当我尝试打开文件夹unsing 7zip或任何其他拉链提取器。请帮忙

      public static void main(String[] args) {
    FileOutputStream fos;
    try {
        fos = new FileOutputStream("D:\\update.zip");

        ZipOutputStream zos = new ZipOutputStream(fos);
         URL url = new URL("http://n3.sdlcdn.com/imgs/b/9/r/SDL468499912_2-8f209.jpg");

        ZipEntry ze = new ZipEntry(url.getFile());
        zos.putNextEntry(ze);
        byte[] data = new byte[300000];
        //   fos.write(data, 0, data.length);
        zos.write(data, 0, data.length);
        zos.closeEntry();
        zos.finish();
        zos.close();
    } catch (Exception ex) {
        Logger.getLogger(Main77.class.getName()).log(Level.SEVERE, null, ex);
    }
}

2 个答案:

答案 0 :(得分:0)

将图像保存为zip格式如下。

public class ZipSaveWorker implements Runnable{

public static ZipOutputStream out=null;
BufferedImage myImage;
private static int counter=0;



public void run() {
    ZipEntry entry=new ZipEntry("video"+counter+".jpg");
    counter++;
    try {
        out.putNextEntry(entry);
        ImageIO.write(myImage, "jpg", out);

    } catch (IOException ex) {
        Logger.getLogger(ZipSaveWorker.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public ZipSaveWorker(BufferedImage image)
{
    if (out==null)
    {
        try {
            out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(new File("images" + File.separator + "video.zip"))));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ZipSaveWorker.class.getName()).log(Level.SEVERE, null, ex);
        }
        counter=0;
    }

    myImage=image;

}

public static void closeStream()
{
    try {
        out.flush();
        out.close();
    } catch (IOException ex) {
        Logger.getLogger(ZipSaveWorker.class.getName()).log(Level.SEVERE, null, ex);
    }
}
}

使用任何Imagedownload图书馆下载图片

答案 1 :(得分:0)

zos.write正在写字节数组的空白缓冲区。

        byte[] data = new byte[300000];

          zos.write(data, 0, data.length);

为什么不初始化较小的字节数组并循环读取下载图像中接收的实际字节以添加到输出流中?

查看在http://www.java-examples.com/create-zip-file-directory-using-zipoutputstream-example

使用zip输出流的一个很好的示例

读取字节数组中的图像数据,并将字节添加到zipoutputstream。