I have a dynamic text file that picks content from a database according to the user's query. I have to write this content into a text file and zip it in a folder in a servlet. How should I do this?
The java.util.zip
package contains classes for creating Zip files from within Java. Would that do what you're looking for?
Look at this example:
final StringBuilder sb = new StringBuilder();
sb.append("Test String");
final File f = new File("d:\\test.zip");
final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f));
ZipEntry e = new ZipEntry("mytext.txt");
out.putNextEntry(e);
byte[] data = sb.toString().getBytes();
out.write(data, 0, data.length);
out.closeEntry();
out.close();
This will create a Zip-File located in the root of D: named 'test.zip' which will contain one single file called 'mytext.txt'. Of course you can add more zip entries and also specify a sub directory like:
ZipEntry e = new ZipEntry("folderName/mytext.txt");
You can find more information about compression with java here:
http://java.sun.com/developer/technicalArticles/Programming/compression/
To write a ZIP file, you use a ZipOutputStream. For each entry that you want to place into the ZIP file, you create a ZipEntry object. You pass the file name to the ZipEntry constructor; it sets the other parameters such as file date and decompression method. You can override these settings if you like. Then, you call the putNextEntry method of the ZipOutputStream to begin writing a new file. Send the file data to the ZIP stream. When you are done, call closeEntry. Repeat for all the files you want to store. Here is a code skeleton:
FileOutputStream fout = new FileOutputStream("test.zip");
ZipOutputStream zout = new ZipOutputStream(fout);
for all files
{
ZipEntry ze = new ZipEntry(filename);
zout.putNextEntry(ze);
send data to zout;
zout.closeEntry();
}
zout.close();