如何在写入文件时压缩文件? [英] How to zip a file while writing to it?

查看:227
本文介绍了如何在写入文件时压缩文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何压缩您要写入的讯息串吗?我试图避免将文件写入磁盘,并且想知道我是否可以压缩数据,因为你正在写入流。

Does anyone know of a way to zip a stream that you are writing to? I'm trying to avoid writing the file to the disk, and was wondering if I can just compress data as you are writing it to the stream.

后面的用例这是原始文件将是非常大,我们想避免将整个事情写入磁盘上解压缩。

The use case behind this is that the raw file is going to be very large and we want to avoid having to write the entire thing unzipped onto the disk.

推荐答案

我认为您会对 ZipOutputStream 。您可以写入该流,然后将其写入压缩文件。

I think you would be interested in ZipOutputStream. You can write to that stream, and then write it out to a zipped file.

此外,请查看本教程使用Java中的压缩(压缩)文件。下面是该教程中的一段代码,它可能是一个有用的插图:

Also, check out this tutorial for working with compressed (zipped) files in Java. Here is a snippet from that tutorial, which might be a helpful illustration:

     BufferedInputStream origin = null;
     FileOutputStream dest = new 
       FileOutputStream("c:\\zip\\myfigs.zip");
     ZipOutputStream out = new ZipOutputStream(new 
       BufferedOutputStream(dest));
     //out.setMethod(ZipOutputStream.DEFLATED);
     byte data[] = new byte[BUFFER];
     // get a list of files from current directory
     File f = new File(".");
     String files[] = f.list();

     for (int i=0; i<files.length; i++) {
        System.out.println("Adding: "+files[i]);
        FileInputStream fi = new 
          FileInputStream(files[i]);
        origin = new 
          BufferedInputStream(fi, BUFFER);
        ZipEntry entry = new ZipEntry(files[i]);
        out.putNextEntry(entry);
        int count;
        while((count = origin.read(data, 0, 
          BUFFER)) != -1) {
           out.write(data, 0, count);
        }
        origin.close();
     }
     out.close();

这篇关于如何在写入文件时压缩文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆