Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generated ZIP file is corrupt / invalid

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.

like image 525
Lazlo Avatar asked Dec 25 '22 16:12

Lazlo


1 Answers

You're writing to the wrong stream.

  // fos.write(data, 0, data.length);
  zos.write(data, 0, data.length);
like image 197
Elliott Frisch Avatar answered Dec 28 '22 05:12

Elliott Frisch