简体   繁体   中英

Java not writing to zip file

I have the following java method which I'm trying to use to create a zip file, which has an existing file written into it (the zip file has the same name, just with the .log extension replaced with .zip) . The zip file is created successfully, however the file is not inside it when it completes.

Here is my code:

private static void zipFile(File fileToZip) {

    final int bufferSize = 2048;
    File zipFile = new File(fileToZip.getAbsolutePath().replaceAll(".log", ".zip"));

    try (FileOutputStream fos = new FileOutputStream(zipFile.getAbsolutePath());
            FileInputStream fis = new FileInputStream(fileToZip);
            ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
            BufferedInputStream origin = new BufferedInputStream(fis, bufferSize)) {

        ZipEntry ze = new ZipEntry(fileToZip.getAbsolutePath());
        zos.putNextEntry(ze);
        byte[] data = new byte[bufferSize];
        int count;
        while ((count = origin.read(data, 0, bufferSize)) != -1) {
            LOGGER.info("WRITING!!!");
            zos.write(data, 0, count);
        }
        zos.closeEntry();

    } catch (IOException e) {
        LOGGER.error("Error: ", e);
    }

}

Any ideas? :)

Change

ZipEntry ze = new ZipEntry(fileToZip.getAbsolutePath());

to

ZipEntry ze = new ZipEntry(fileToZip.getName());

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