Discussion Locked

Java code for writing a zip file

0 helpful
1 reply
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Hi folks,
I have dynamically created certain files and would like to zip them.I have just ahd a look at the java.util.zip package but would like to know if anyone already has a code for writing into a zip file it wud b very useful.

1 reply

by bayard-generationjava

Well, the formatting will die, so you'll have to redo that.
But, from my GenJavaCore library:

[code]
package com.generationjava.io;

import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.io.IOException;
import java.io.OutputStream;

/**
* Makes creating Zip files easier.
*/
final public class ZipW {

private ZipOutputStream zipout = null;

/**
* Provide the OutputStream that this Zip will be
written to.
*/
public ZipW(OutputStream out) {
this.zipout = new ZipOutputStream( out );
}

/**
* Add the passed in String data to the Zip under the
specified
* filename.
*/
public boolean addFile(String filename, String
contents) {
// test if this dir has been written to yet?
try {
ZipEntry entry = new ZipEntry(filename);
entry.setTime(System.currentTimeMillis());
entry.setSize(contents.length()); // *2?
zipout.putNextEntry(entry);

zipout.write(contents.getBytes());

zipout.closeEntry();
return true;
} catch(ZipException ze) {
ze.printStackTrace();
return false;
} catch(IOException ioe) {
ioe.printStackTrace();
return false;
}

}

/**
* Close the zip file.
*/
public void close() {
try {
zipout.close();
} catch(ZipException ze) {
ze.printStackTrace();
return;
} catch(IOException ioe) {
ioe.printStackTrace();
return;
}
}

}
[/code]

This discussion is closed to new replies.