I'm trying to create a simple ZIP file in Java, but once generated, I can't open it with either Windows Explorer or 7-zip, as they say the file is invalid / unrecognized / corrupted.
However, I'm following all the tutorials I've seen and using a very simple code, so I don't see where I went wrong. Here's the simplest snippet I could think of to reproduce the problem:
FileOutputStream fos = new FileOutputStream("test.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = new ZipEntry("test.txt");
zos.putNextEntry(ze);
byte[] data = "content".getBytes();
fos.write(data, 0, data.length);
zos.closeEntry();
zos.finish();
zos.close();
Did I miss a setting somewhere?
For reference, I've uploaded the test.zip
file here.
You're writing to the wrong stream.
// fos.write(data, 0, data.length);
zos.write(data, 0, data.length);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With