如何在 Java 中创建一个 zip 文件

新手上路,请多包涵

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

原文由 Ashish Agarwal 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 562
2 个回答

看这个例子:

 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 的 zip,其中将包含一个名为 mytext.txt 的单个文件。当然,您可以添加更多 zip 条目并指定一个子目录,如下所示:

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

您可以 在此处 找到有关使用 Java 进行压缩的更多信息。

原文由 Chris 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

Java 文档:ZipFileSystem 提供程序

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

原文由 Sivabalan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题