Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

producing an empty zip file java

Tags:

java

zip

I'm currently writing a function what would create a zip file, which will be used in other functionality. Below it is my function's code:

public void createZip(){

        try{
            String outfile = this.filename + ".zip";
            //input file
            FileInputStream input = new FileInputStream(this.filename);
            //output file
            ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(outfile));
            //name the file inside the zip file
            System.out.println(this.filename);
            zip.putNextEntry(new ZipEntry(this.filename));

            byte[] buffer = new byte[this.BUFFER];
            int len;
            //copy the file to the zip
            while((len= input.read(buffer)) > 0){
                System.out.println(len);
                zip.write(buffer, 0, len);
            }
            zip.closeEntry();
            zip.flush();
            input.close();
            zip.close();
            this.filename += ".zip";
        }
        catch(IOException e){
            e.printStackTrace();
        }

    }

I have tried to debug, but I couldn't find the source of this problem. The function runs without any further problems, but the zip file produced it is an empty one.

like image 877
cybertextron Avatar asked Dec 09 '22 23:12

cybertextron


1 Answers

You must close the entry using ZipOutputStream#closeEntry() prior to closing the output stream, or the entry is never confirmed to have been written entirely.

Also, the name of the ZipEntry cannot be the entire path; i.e, it should be dog.png instead of C:\Users\Admin\Documents\dog.png. This issue will pass by without an exception, and will cause the data from the file to be compressed directly into the zip, rather than into the zip as a compressed file.

like image 164
FThompson Avatar answered Dec 11 '22 11:12

FThompson