2013-05-14 120 views
8

我想創建多個圖像文件的zip文件。我成功地創建了所有圖像的zip文件,但不知何故,所有圖像都被掛起到950字節。我不知道這裏出了什麼問題,現在我無法打開被壓縮到該zip文件中的圖像。如何創建多個圖像文件的zip文件

這是我的代碼。任何人都可以讓我知道這裏發生了什麼?

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())>0) 

這樣:

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

並設置緩衝區大小爲1024字節:

b=new byte[1024]; 
+0

感謝它的工作得很好你已經解決了問題,謝謝兄弟感謝很多....:D – 2013-05-14 15:33:00

+1

如果你認爲這個答案是合適的,接受它。 – hoaz 2013-05-14 15:39:22

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()); – 2014-05-19 05:02:10

+0

嗨 - 你是對的,爲了保持文件夾結構,最好使用* .getCanonicalName()我已經適應了我的答案 - 謝謝。 – salocinx 2014-05-19 11:28:15

+0

嗨。我想知道(我)爲什麼我們沒有清除out.write語句後的緩衝區,不會緩衝區溢出? (ii)對於小於1MB的文件大小,通常應保留的緩衝區大小是多少? – 2016-12-30 04:38:39

相關問題