2013-08-28 63 views
3

我正在寫代碼來創建txt文件,並且完全寫入該txt文件後意味着完全關閉txt文件而不是zip文件。但是,我不爲什麼,就不會等到文件關閉文件之前關閉它壓縮它.. 請幫我完整寫入文件後的Java代碼壓縮文件

這裏是我的代碼:

import java.io.BufferedWriter; 
import java.io.FileOutputStream; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.util.zip.ZipEntry; 
import java.util.zip.ZipOutputStream; 


public class zipfile { 

    /** 
    * @param args 
    * @throws IOException 
    */ 
    public static void main(String[] args) throws IOException { 
     // TODO Auto-generated method stub 

     BufferedWriter bfAllBWPownmanmainfest = null; 
     String mainfest = "file\\" + "fileforzip" + ".txt"; 
     bfAllBWPownmanmainfest = new BufferedWriter(new FileWriter(mainfest)); 

     bfAllBWPownmanmainfest.write("jdshsdksdkhdshksd\n"); 
     bfAllBWPownmanmainfest.write("jdshsdksdkhsdfsdfsddshksd\n"); 
     bfAllBWPownmanmainfest.write("jdshsdksdsdfdskhdshksd\n"); 
     bfAllBWPownmanmainfest.write("jdshsdksddsfdskhdshksd\n"); 
     bfAllBWPownmanmainfest.write("jdshsdksddsfdskhdshksd\n"); 
     bfAllBWPownmanmainfest.write("jdshsdksdsdfdskhdshksd\n"); 
     bfAllBWPownmanmainfest.write("jdshsdksddsfsdkhdshksd\n"); 

     bfAllBWPownmanmainfest.flush(); 
     bfAllBWPownmanmainfest.close(); 

     //After close file than zip that!! please help me Thanks 

     FileOutputStream fout = new FileOutputStream("test.zip"); 
     ZipOutputStream zout = new ZipOutputStream(fout); 

     ZipEntry ze = new ZipEntry(mainfest); 
     zout.putNextEntry(ze); 
     zout.closeEntry(); 
     zout.close(); 

    } 

} 

接近bfAllBWPownmanmainfest.close後();比拉鍊,我怎麼能做到這一點,請高級幫助我感謝!它創建空的zip文件,它並沒有等到文件完全關閉! 請幫助我!謝謝!!

+0

只是一個fyi,關閉刷新緩衝區,所以調用刷新然後關閉是多餘的。 – Grammin

+0

參考這個http://stackoverflow.com/questions/1091788/how-to-create-a-zip-file-in-java 你必須寫信給ZipOutputStream。 – sri

回答

3

您已經創建了ZipEntry,但實際上並沒有將任何字節寫入輸出zip文件。您需要讀取文件的InputStream,並在putNextEntry(ZipEntry)後寫入ZipOutputStream

FileInputStream in = new FileInputStream(mainfest); 
byte[] bytes = new byte[1024]; 
int count; 

FileOutputStream fout = new FileOutputStream("test.zip"); 
ZipOutputStream zout = new ZipOutputStream(fout); 

ZipEntry ze = new ZipEntry(mainfest); // this is the name as it will appear if you opened the zip file with WinZip or some other zip manager 
zout.putNextEntry(ze); 

while ((count = in.read(bytes)) > 0) { 
    zout.write(bytes, 0, count); 
} 

zout.closeEntry(); 
zout.close(); 
+0

感謝您的幫助!但是當你打開zip文件時,它也說文件路徑,有沒有辦法,我們可以刪除它,因爲當我壓縮該zip文件中的其他文件時,它做錯了!請幫幫我!! – user2726811

+0

@ user2726811不客氣。 –

+0

感謝您的幫助!但是當你打開zip文件時,它也說文件路徑,有沒有辦法,我們可以刪除它,因爲當我壓縮該zip文件中的其他文件時,它做錯了!請幫幫我!!當我壓縮其中的其他文件時,它會創建所有文件夾和zip文件! – user2726811

0

你不不需要ZipEntry。嘗試此代碼之前bfAllBWPownmanmainfest.close();的語句。

ZipOutputStream zout = new ZipOutputStream(fout); 
    int size = 0; 
    byte[] b = new byte[1000]; 
    while ((size = bfAllBWPownmanmainfest.read(b)) > 0) { 
     zout.write(b, 0, size); 
    } 
    zout.close(); 
    bfAllBWPownmanmainfest.close();