1

I am having an issue putting a folder in a zip file I am trying to create. While the path is valid, when I run the code it gives me a File Not Found Exception. Here is my code

String outFilename = "outfile.zip";
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename)); 
byte[] buf = new byte[1024];
File file = new File("workspace");
System.out.println(file.isDirectory());
System.out.println(file.getAbsolutePath());
FileInputStream in = new FileInputStream(file.getAbsolutePath());
out.putNextEntry(new ZipEntry(file.getAbsolutePath()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}

out.closeEntry();
in.close();
  • are you trying to add a single empty folder, or are you trying t add a folder with all containing files in it recursively? – Oleg Mikheev Nov 08 '11 at 20:16

1 Answers1

1

You're trying to read bytes from a directory; it doesn't work like that. The exception says as much, too.

You need to add the directory, then add each file within the directory. If you use the file path you don't need to add the directory explicitly.

I'd be very wary of using the absolute path as the zip entry; better to use a relative path so you can unzip it anywhere and not risk overwriting something you want.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • so I need to pretty much totally recreate the file structure that is within the directory, or do I just need to do the top level? – Jeremy Kaplan Nov 08 '11 at 20:18
  • @JeremyKaplan You'd need to recursively spin through the directory and add each entry individually. It's not significantly more difficult, though. – Dave Newton Nov 08 '11 at 20:21
  • 1
    @JeremyKaplan get some copy-n-paste practice man http://www.java-examples.com/create-zip-file-directory-recursively-using-zipoutputstream-example – Oleg Mikheev Nov 08 '11 at 20:24
  • mkdirs() function for File object will create all directories required for your destination File. http://download.oracle.com/javase/6/docs/api/ – Michael K Nov 08 '11 at 20:29
  • found this which works http://stackoverflow.com/questions/1399126/java-util-zip-recreating-directory-structure – Jeremy Kaplan Nov 08 '11 at 20:31
  • If you need to recreate an empty folder (eg. logs) just create a single zero byte file in that path of the zip file (eg. logs\empty.txt) – Chris Nava Nov 08 '11 at 21:43
  • @ChrisNava You could also use `path/.` and skip the empty file. – Dave Newton Nov 08 '11 at 21:46