2013-05-14 15 views
8

複数のイメージファイルのzipファイルを作成しようとしています。私はすべての画像のzipファイルを作成するのに成功しましたが、何とかすべての画像が950バイトにぶら下がっています。私は何がここで間違っているのか分からず、今はその画像をそのzipファイルに圧縮して開くことができません。複数のイメージファイルのzipファイルを作成する方法

ここに私のコードです。誰が私にここで何が起こっているのか教えてもらえますか

while((length=fin.read())>0) 

これに:この

String path="c:\\windows\\twain32"; 
File f=new File(path); 
f.mkdir(); 
File x=new File("e:\\test"); 
x.mkdir(); 
byte []b; 
String zipFile="e:\\test\\test.zip"; 
FileOutputStream fout=new FileOutputStream(zipFile); 
ZipOutputStream zout=new ZipOutputStream(new BufferedOutputStream(fout)); 


File []s=f.listFiles(); 
for(int i=0;i<s.length;i++) 
{ 
    b=new byte[(int)s[i].length()]; 
    FileInputStream fin=new FileInputStream(s[i]); 
    zout.putNextEntry(new ZipEntry(s[i].getName())); 
    int length; 
    while((length=fin.read())>0) 
    { 
     zout.write(b,0,length); 
    } 
    zout.closeEntry(); 
    fin.close(); 
} 
zout.close(); 

答えて

9

変更

while((length=fin.read(b, 0, 1024))>0) 

と設定バッファサイズ1024バイト:これは私がいつも使用して私のzip機能

b=new byte[1024]; 
+0

おかげで問題は解決しました。ありがとうございました.D –

+1

この回答が適切だと思われる場合は、それを受け入れてください。過去に尋ねたすべての質問にも同じことが当てはまります – hoaz

14

です任意のファイル構造に対して:

public static File zip(List<File> files, String filename) { 
    File zipfile = new File(filename); 
    // Create a buffer for reading the files 
    byte[] buf = new byte[1024]; 
    try { 
     // create the ZIP file 
     ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile)); 
     // compress the files 
     for(int i=0; i<files.size(); i++) { 
      FileInputStream in = new FileInputStream(files.get(i).getCanonicalName()); 
      // add ZIP entry to output stream 
      out.putNextEntry(new ZipEntry(files.get(i).getName())); 
      // transfer bytes from the file to the ZIP file 
      int len; 
      while((len = in.read(buf)) > 0) { 
       out.write(buf, 0, len); 
      } 
      // complete the entry 
      out.closeEntry(); 
      in.close(); 
     } 
     // complete the ZIP file 
     out.close(); 
     return zipfile; 
    } catch (IOException ex) { 
     System.err.println(ex.getMessage()); 
    } 
    return null; 
} 
+0

このサンプルはありがたいですが、この行を変更しなければならないことを除けば、ありがとうございます:FileInputStream in = new FileInputStream(files.get(i).getCanonicalName()); –

+0

こんにちは - フォルダ構造を維持するために、* .getCanonicalName()を使用する方が良いです。私はそれを私の答えに適応させました - ありがとうございます。 – salocinx

+0

こんにちは。私は、なぜ私たちがout.writeステートメントの後にバッファをクリアしていないのだろうと思っています。 (ii)1 MB未満のファイルサイズのために一般に保持されるバッファサイズはどのくらいでしょうか? –

関連する問題