Adam Smith Adam Smith - 1 month ago 15
Java Question

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? :)

Answer

Change

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

to

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