tangowayne
asked on
Create Zip file for Mac while preserving folder directory structure
Hi,
In my application I am zipping up a directory structure on the server (Linux or PC) and providing a link for the user to download the zip file. It is important that when the user extract the files the full tree is preserved. I am using java.util.zip.ZipEntry & java.util.zip.ZipOutputStr
I am also looking for ways to creat zip file with "relative" path rather than "absolute" but haven't figure that out yet. My code is running under Tomcat 4.1. Could this be my problem?
Here's the main part of my code:
public boolean executeZip() throws
IOException {
String inputFiles = "D:\\download\\InDir\\08_2
String outZipFileName = "TestZip.zip";
String outputZipFilePath = "D:\\download\\OutDir" + "\\" + outZipFileName;
System.out.println("Zippin
try {
System.out.println("Output
//create a ZipOutputStream to zip the data to
ZipOutputStream zos = new
ZipOutputStream(new FileOutputStream(outputZip
zipDir(inputFiles, zos);
//close the stream
zos.close();
File file = new File(outputZipFilePath);
// Get the number of bytes in the file
outputZipFileSize = file.length() / 1024;
}
catch (InterruptedException e) {
setRunning(false);
return false;
}
catch (Exception e) {
//handle exception
System.out.println(e);
return false;
}
return true;
}
public void zipDir(String dir2zip, ZipOutputStream zos) throws Exception {
//create a new File object based on the directory we have to zip File
File zipDir = new File(dir2zip);
//get a listing of the directory content
String[] dirList = zipDir.list();
byte[] readBuffer = new byte[2156];
int bytesIn = 0;
//loop through dirList, and zip the files
for (int i = 0; i < dirList.length; i++) {
File f = new File(zipDir, dirList[i]);
if (f.isDirectory()) {
//if the File object is a directory, call this
//function again to add its content recursively
String filePath = f.getPath();
zipDir(filePath, zos);
//loop again
continue;
}
//if we reached here, the File object f was not a directory
//create a FileInputStream on top of f
FileInputStream fis = new FileInputStream(f);
//create a new zip entry
ZipEntry anEntry = new ZipEntry(f.getPath());
//place the zip entry in the ZipOutputStream object
zos.putNextEntry(anEntry);
//now write the content of the file to the ZipOutputStream
while ( (bytesIn = fis.read(readBuffer)) != -1) {
zos.write(readBuffer, 0, bytesIn);
}
//close the Stream
fis.close();
}
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks Webstorm and orangehead911. It makes sense to me now and it's working beautifully.
=-)
:-)
\t