2016-09-01 8 views
1

私はzip形式で画像をダウンロードしようとしていますが、以下のコードを実行しようとしているときに7zipやその他のzip抽出プログラムのフォルダを開こうとすると「圧縮されたフォルダは無効です。助けてくださいjavaを使用しているzipで画像をダウンロードする

 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); 
    } 
} 
+0

これを確認してくださいhttp://stackoverflow.com/questions/3428396/how-to-save-images-into-a-zip-file –

+0

ファイル内に実際の画像ではない300,000個の空白しか書かれていません。 – Jens

答えて

0

イメージを次のように保存してください。

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); 
    } 
} 
} 

そして

+0

私はBufferedImageを使ってみました。myImage = ImageIO.read(新しいURL( "http://n3.sdlcdn.com/imgs/b/9/r/SDL468499912_2-8f209.jpg")); ZipSaveWorker zip =新しいZipSaveWorker(myImage); zip.run(); ...出力ZIPファイルは0バイトです。 –

0

zos.writeは、バイト配列の空白バッファを書き込んでいる任意のImagedownloadのlibararyを使用して画像をダウンロードしてください。

 byte[] data = new byte[300000]; 

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

出力ストリームに追加するには、ダウンロードしたイメージで受け取った実際のバイトをループしてループしないのはなぜですか?

バイト配列内の画像データを読み取り、zipoutputstreamにバイトを追加http://www.java-examples.com/create-zip-file-directory-using-zipoutputstream-example

にZIP出力ストリームを使用しての良い例を参照してください。

関連する問題