问题

我有一个动态文本文件,根据用户的查询从数据库中选择内容。我必须将此内容写入文本文件并将其压缩到servlet中的文件夹中。我该怎么做?


#1 热门回答(161 赞)

看看这个例子:

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条目,还可以指定子目录,如:

ZipEntry e = new ZipEntry("folderName/mytext.txt");

你可以在此处找到有关使用java压缩的更多信息:
http://www.oracle.com/technetwork/articles/java/compress-1565076.html


#2 热门回答(83 赞)

Java 7内置了ZipFileSystem,可用于从zip文件创建,写入和读取文件。
Java Doc: ZipFileSystem Provider

Map<String, String> env = new HashMap<>(); 
env.put("create", "true");

URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");

try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
    Path externalTxtFile = Paths.get("/codeSamples/zipfs/SomeTextFile.txt");
    Path pathInZipfile = zipfs.getPath("/SomeTextFile.txt");          
    // copy a file into the zip file
    Files.copy(externalTxtFile, pathInZipfile, StandardCopyOption.REPLACE_EXISTING); 
}

#3 热门回答(27 赞)

要编写ZIP文件,请使用ZipOutputStream。对于要放入ZIP文件的每个条目,可以创建ZipEntry对象。你将文件名传递给ZipEntry构造函数;它设置其他参数,如文件日期和解压缩方法。你可以根据需要覆盖这些设置。然后,调用ZipOutputStream的putNextEntry方法开始编写新文件。将文件数据发送到ZIP流。完成后,调用closeEntry。对要存储的所有文件重复此操作。这是一个代码框架:

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();

原文链接