4

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.

Lazlo
  • 8,518
  • 14
  • 77
  • 116

1 Answers1

10

You're writing to the wrong stream.

  // fos.write(data, 0, data.length);
  zos.write(data, 0, data.length);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Well here's an hour well wasted! Thanks for the quick reply (I'll accept when S/O lets me). – Lazlo Dec 17 '13 at 03:42