0

I have stored blobs of multiple files in the database. User should be able to click on a link and should be able to download all the files as zipped. But before that I want to provide a folder structure to group those files. Say, a base folder followed by nested folders and related files. I followed the link below, looks like, I need to first create a physical dir structure for the same and then zip that structure?

http://www.journaldev.com/957/java-zip-example-to-zip-single-file-and-a-directory-recursively

Forkmohit
  • 733
  • 3
  • 12
  • 31

1 Answers1

1

Files in a zip directory are abstracted as ZipEntry objects in Java. Those have names that corresponds to the path relative to the directory where you unpack the zip file. Directories in a zip file are simply entries whose name ends with /. This way, you can also view a zip file as a plain list of binary data entries whose names reflect the directory structure. So you don't have to create a folder structure on you hard drive and zip it but you can write directly from the database to the ZipOutputStream:

  • Create each folder as a ZipEntry with no content and a name ending with /.
  • Instead of using a FileInputStream for reading from files on the hard drive, write the output of resultSet.getBinaryStream("blobcolumn") directly to the entry.
esel
  • 901
  • 9
  • 20
  • Thanks! so, to create a folder I did, new ZipEntry("images/"). But how to add files to images? new ZipEntry("images/filename") ? – Forkmohit Oct 13 '15 at 08:29
  • 1
    Yes, exactly. The entry name is the complete relative path of the "file". – esel Oct 13 '15 at 08:42
  • are you still alive ;) ? I got 1 more question! – Forkmohit Oct 30 '15 at 11:50
  • I was reversing the process stated above, i.e, extracting files and folders from the zip. I was able to read all the zip-entries for the file ziped via the utility. But when I tried to read the zip-entries from the zip generated by above method I got **java.util.zip.ZipException: error in opening zip file** exception. – Forkmohit Oct 30 '15 at 13:43
  • I can't really say much about that without code. It can have many reasons. You can post a new question with the relevant code, if can't figure out a solution. But this question (http://stackoverflow.com/questions/325202/java-util-zip-zipexception-error-in-opening-zip-file) might be a good read. – esel Oct 30 '15 at 14:55
  • In my investigation, I found that the file-separator(/) was cause of the issue. I switched to (\\) and it worked. My dev env is ubuntu. I need to check with other OSs and zip utils. – Forkmohit Oct 31 '15 at 06:34