天天看点

java创建空zip文件,如何在Java中创建zip文件

java创建空zip文件,如何在Java中创建zip文件

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?

解决方案

Look at this example:

StringBuilder sb = new StringBuilder();

sb.append("Test String");

File f = new File("d:\\test.zip");

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: