如何在Java中创建zip文件 [英] How to create a zip file in Java
问题描述
我有一个动态文本文件,可根据用户的查询从数据库中选择内容。我必须将此内容写入文本文件并将其压缩到servlet中的文件夹中。我该怎么做?
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?
推荐答案
看看这个例子:
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();
这将创建位于D的根目录中的Zip文件:名为test.zip的将包含一个名为'mytext.txt'的文件。当然,你可以添加更多的zip条目,并指定一个子目录,如:
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");
您可以在此处找到有关使用java进行压缩的更多信息:
You can find more information about compression with java here:
http://www.oracle.com/technetwork/ articles / java / compress-1565076.html
这篇关于如何在Java中创建zip文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!