当使用 Java 读入压缩文件时,如何通过管道将输入流传输到压缩文件?

发布于 2024-07-05 10:17:20 字数 98 浏览 8 评论 0原文

我想要执行一个程序,并在它运行时读取它的输出并将输出输出到压缩文件中。 程序的输出可能非常大,因此我们的想法是不要在内存中保存太多内容 - 只是在我得到它时将其发送到 zip 中。

I'm wanting to execute a program and as it runs read in it's output and pipe out the output into a zipped file. The output of the program can be quite large so the idea is to not hold too much in memory - just to send it to the zip as I get it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淑女气质 2024-07-12 10:17:20
ZipOutputStream targetStream = new ZipOutputStream(fileToSaveTo);
ZipEntry entry = new ZipEntry(nameOfFileInZipFile);
targetStream.putNextEntry(entry);

byte[] dataBlock = new byte[1024];
int count = inputStream.read(dataBlock, 0, 1024);
while (count != -1) {
    targetStream.write(dataBlock, 0, count);
    count = inputStream.read(dataBlock, 0, 1024);
}

换句话说:

  1. 您创建一个 ZipOutputStream,并为其提供您想要写入的文件。
  2. 您创建一个 ZipEntry,它构成该 zip 文件中的一个文件。
    即当你打开 myFile.zip 时,里面有 3 个文件,每个文件都是一个 ZipEntry

  3. 您将 ZipEntry 放入您的 ZipOutputStream

  4. 创建用于将数据读入的字节缓冲区。
  5. inputStream 读入字节缓冲区,并记住计数。
  6. 虽然 count 不是 -1,但将该字节 byffer 写入您的 zipStream
  7. 阅读下一行。

完成后关闭流。 将其包装在您认为合适的方法中。

ZipOutputStream targetStream = new ZipOutputStream(fileToSaveTo);
ZipEntry entry = new ZipEntry(nameOfFileInZipFile);
targetStream.putNextEntry(entry);

byte[] dataBlock = new byte[1024];
int count = inputStream.read(dataBlock, 0, 1024);
while (count != -1) {
    targetStream.write(dataBlock, 0, count);
    count = inputStream.read(dataBlock, 0, 1024);
}

In otherwords:

  1. You create a ZipOutputStream, giving it the file you want to write to.
  2. You create a ZipEntry, which constitutes a file within that zip file.
    i.e. When you open myFile.zip, and there are 3 files in there, each file is a ZipEntry.

  3. You put that ZipEntry into your ZipOutputStream

  4. Create a byte buffer to read your data into.
  5. Read from your inputStream into your byte buffer, and remember the count.
  6. While the count is not -1, write that byte byffer to your zipStream.
  7. Read the next line.

Close out your streams when you are done. Wrap it in a method as you see fit.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文