Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

ZipOutputStream and Directories  RSS feed

 
dave taubler
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've begun working on a back-up mechanism for my application's data, which simply involves using java.util.zip to compress all of my data and write it out to a ZIP file. Using a ZipOutputStream seems very easy in this manner, except... all of my data files are stored in distinct directories. But when I write all of those files to a ZIP archive, and then open up the archive, the directory structure is gone, and they are all lumped together.
To illustrate what I mean:
Originally, my data would be stored something like this:
[directory] Week1
- [file] Day1-1
- [file] Day1-2
- [file] Day1-3
- [file] Day1-4
[directory] Week2
- [file] Day2-1
- [file] Day2-2
- [file] Day2-3
[directory] Week3
- [file] Day3-1
- [file] Day3-2
- [file] Day3-3
- [file] Day3-4
- [file] Day3-5
... etc...
So I use methods like File.listFiles() to create an array of all of these files, and then loop through the array to add a new ZipEntry and then write out each file into the ZIP archive.
When I look at/uncompress the resulting ZIP archive, I see this file structure:
[file] Day1-1
[file] Day1-2
[file] Day1-3
[file] Day1-4
[file] Day2-1
[file] Day2-2
[file] Day2-3
[file] Day3-1
[file] Day3-2
[file] Day3-3
[file] Day3-4
...etc...
But I really want the directory structure to remain intact.
Any ideas on what I might be doing wrong? Thanks very much in advance!
 
dave taubler
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I just went out and answered my question. So if anyone runs into the problem I described in the first post, the solution lies in ZipEntry object. As you create a ZipEntry object that is used in adding an entry to a ZIP file, it is apparently the name that you assign to the ZipEntry object that determines what directory, if any, that that file belongs in.

For example, I was creating ZipEntries like this:
... new ZipEntry("file.dat");
If I wanted it to stay in the directory "dir1", I should've done:
... new ZipEntry("dir1/file.dat");
In other words, do
... new ZipEntry(file.getPath());
not
... new ZipEntry(file.getName());
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!