我有一个动态文本文件,它根据用户的查询从数据库中挑选内容。我必须将这些内容写入一个文本文件,然后将其压缩到servlet的文件夹中。我该怎么做呢?
发布于 2009-07-07 11:28:30
看看这个例子:
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:
的根目录下创建一个名为test.zip
的压缩包,其中将包含一个名为mytext.txt
的文件。当然,您可以添加更多的zip条目,也可以指定一个子目录,如下所示:
ZipEntry e = new ZipEntry("folderName/mytext.txt");
您可以找到有关使用Java here进行压缩的更多信息。
发布于 2015-10-06 13:41:53
Java7内置了ZipFileSystem,可以用来创建、写入和读取压缩文件。
Java Doc: ZipFileSystem Provider
Map<String, String> env = new HashMap<>();
// Create the zip file if it doesn't exist
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);
}
发布于 2009-07-07 11:39:15
要编写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();
https://stackoverflow.com/questions/1091788
复制相似问题