简体   繁体   中英

Why is my file doesn't read to a zip archive

I have a code snippet, that in theory should read a path to an archive first, when write a file to the archive. (But that thing takes zip and for instance some txt file, and really move it to zip, but the file is empty) First, i thought this thing doesn't work since i didn't close streams, but now i use try-with, so the problem should be gone, but it is not.

 public void createZip(Path source) throws Exception
    {
        try(ZipInputStream zipIn = new ZipInputStream(Files.newInputStream(source));
        ZipOutputStream zipOut = new ZipOutputStream(Files.newOutputStream(zipFile)))
        {
            ZipEntry zipEntry = new ZipEntry(source.getFileName().toString());
            zipOut.putNextEntry(zipEntry);

            int data;

            while((data = zipIn.read()) > 0)
            {
                zipOut.write(data);
            }
        }
    }

To use correctly the ZipOutputStream after adding the entry you need to flush the zip. Try adding the following at the endo of your method:

zipOut.flush();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM