Zipping a folder including subfolders problem.
807603Sep 18 2007 — edited Oct 18 2007Hey guys & girls,
I am currently working on a little tool that will alter the contents of Word2007 files by extracting the XML file out of the docx file, altering it using XSLT and then re-zip the files and rename to original docx format.
The issue I am having is that when I rezip the 19 files of the docx after I have successfully completed the previous steps and then compare it with the same files zipped up using Winzip, the archives differ.
When I hover over the Winzip generated file in explorer the preview displays that there are "25 files and folders" (19 files, 6 folders).
When I do the same with the Java generated zip file it displays "19 files and folders".
When both archives are extracted the results is identical and all the folders etc. are extracted as they should be yet when both are renamed to .docx and opened in word only the Winzip version works.
Does anyone know if there is a trigger to add the actual folder to the zip file in Java? Rather than just adding the file with the full path?
If anyone can help with this I would be eternally grateful.
The code is also below:
-----
import java.io.*;
import java.util.zip.*;
public class zipFile
{
public zipFile(){}
public void zipUp(String folder)
{
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
try
{
fileWriter = new FileOutputStream("output.zip");
zip = new ZipOutputStream(fileWriter);
}
catch (Exception ex)
{
ex.printStackTrace();
System.exit(0);
}
addFolderToZip("", folder, zip);
try
{
zip.flush();
zip.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)
{
File folder = new File(srcFolder);
String fileListe[] = folder.list();
try
{
int i = 0;
while (true)
{
addToZip(path+"/"+folder.getName(), srcFolder+"/"+fileListe, zip);
i++;
}
}
catch (Exception ex) {}
}
private void addToZip(String path, String srcFile, ZipOutputStream zip)
{
File folder = new File(srcFile);
if (folder.isDirectory())
{
addFolderToZip(path, srcFile, zip);
}
else
{
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
try {
FileInputStream in = new FileInputStream(srcFile);
if(path.indexOf("docExtract") != 0)
{
int end = path.length();
String cutPath = path.substring(11, end);
//System.out.println(cutPath +"/"+ folder.getName());
zip.putNextEntry(new ZipEntry(cutPath +"/"+ folder.getName()));
}
else
{
zip.putNextEntry(new ZipEntry(path +"/"+ folder.getName()));
}
while ((len = in.read(buf)) > 0)
{
zip.write(buf, 0, len);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
}
-----