Java Dailly Tip: Java code to zip file after write file completely

Java Dailly Tip: Java code to zip file after write file completely

Problem

I am writing some code to create a txt file and after completely writing in that txt file, completely close the txt file and then zip that file. But, I don't why, it does not wait until file close before file close it zip it.. Here is my code:

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

}

After close bfAllBWPownmanmainfest.close(); then zip it, how can I do that. It creates empty zip file, it didn't wait until file close completely!

Solution

You've created a ZipEntry, but haven't actually written any bytes to the output zip file. You need to read from an InputStream of your file and write to your ZipOutputStream after you've putNextEntry(ZipEntry).

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

Share this Post