Hello there. While trying to zip an archive using the java.util.zip I ran into a lot of problems most of which I solved. Now that I finally get some output I struggle with getting the "right" output. I have an extracted ODT file (directory would be more fitting a description) to which I did some modifications. Now I want to compress that directory as to recreate the ODT file structure. Zipping the directory and renaming it to end with .odt works fine so there should be no problem.
The main problem is that I lose the internal structure of the directory. Everything becomes "flat" and I do not seem to find a way to preserve the original multi-layered structure. I would appreciate some help on this as I can not seem to find the problem.
Here are the relevant code snippets:
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
FILEPATH.substring(0, FILEPATH.lastIndexOf(SEPARATOR) + 1).concat("test.zip")));
compressDirectory(TEMPARCH, out);
The SEPARATOR is the system file separator and the FILEPATH is the filepath of the original ODT which I will override but have not done here for testing purposes. I simply write to a test.zip file in the same directory.
private void compressDirectory(String directory, ZipOutputStream out) throws IOException
{
File fileToCompress = new File(directory);
// list contents.
String[] contents = fileToCompress.list();
// iterate through directory and compress files.
for(int i = 0; i < contents.length; i++)
{
File f = new File(directory, contents[i]);
System.out.println(f.getPath());
// testing type. directories and files have to be treated separately.
if(f.isDirectory())
{
// add empty directory
out.putNextEntry(new ZipEntry(f.getName() + SEPARATOR));
// initiate recursive call
compressDirectory(f.getPath(), out);
// continue the iteration
continue;
}else{
// prepare stream to read file.
FileInputStream in = new FileInputStream(f);
// create ZipEntry and add to outputting stream.
out.putNextEntry(new ZipEntry(f.getName()));
// write the data.
int len;
while((len = in.read(data)) > 0)
{
out.write(data, 0, len);
}
out.flush();
out.closeEntry();
in.close();
}
}
}
The directory that contains the files to zip is somewhere in the user space and not in the same directory as the resulting file. I assume this could be trouble but I can not really see how. Also I figured that the problem could be in using the same stream for outputting but again I can not see how. I saw in some examples and tutorials that they use getpath() instead of getname() but changing that gives me an empty zip file.
Thank you very much for your help and thank you for correcting my formating!