简体   繁体   English

Java未写入zip文件

[英]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) . 我尝试使用以下java方法来创建一个zip文件,该文件中已写入一个现有文件(该zip文件具有相同的名称,只是将.log扩展名替换为.zip)。 The zip file is created successfully, however the file is not inside it when it completes. zip文件已成功创建,但是完成后不在其中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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