Generated ZIP file is corrupt / invalid

2.8k views Asked by At

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.

1

There are 1 answers

1
Elliott Frisch On BEST ANSWER

You're writing to the wrong stream.

  // fos.write(data, 0, data.length);
  zos.write(data, 0, data.length);