【问题标题】:Compressing an input stream Java压缩输入流 Java
【发布时间】:2012-10-27 08:01:37
【问题描述】:

老实说,这不应该有这么多问题,但我肯定遗漏了一些明显的东西。

我可以使用GZIPOutputStream 很好地压缩文件,但是当我尝试直接获取输入时(不是来自文件,而是来自管道或其他东西),当我去调用 gunzip -d 在我的文件上查看它是否正确解压缩,它告诉我它立即运行到文件末尾。基本上,我希望这些工作

echo foo | java Jgzip >foo.gz

java Jzip <test.txt >test.gz

而且不能保证这些都是字符串,所以我们逐字节读取。我以为我可以使用System.in and System.out,但这似乎不起作用。

public static void main (String[] args) {
    try{
        BufferedInputStream bf = new BufferedInputStream(System.in);
        byte[] buff = new byte[1024];
        int bytesRead = 0;

        GZIPOutputStream gout = new GZIPOutputStream (System.out);

        while ((bytesRead = bf.read(buff)) != -1) {
            gout.write(buff,0,bytesRead);
        }
    }
    catch (IOException ioe) {
        System.out.println("IO error.");
        System.exit(-1);    
    }
    catch (Throwable e) {
        System.out.println("Unexpected exception or error.");
        System.exit(-1);
    }
}

【问题讨论】:

  • 除了下面的答案,我建议使用System.err.println 来获取错误消息,否则,您的错误消息将写入gz 文件。

标签: java io gzip


【解决方案1】:

我建议:

OutputStream gout= new GZIPOutputStream( System.out );
System.setOut( new PrintStream( gout ));              //<<<<< EDIT here
while(( bytesRead = bf.read( buff )) != -1 ) {
   gout.write(buff,0,bytesRead);
}
gout.close(); // close flush the last remaining bytes in the buffer stream

【讨论】:

  • 不幸的是,setOut 似乎需要一个 PrintStream 而 gout 是一个 OutputStream。
  • 删除System.setOut(gout); 并给@Aubin 打勾!
  • 如果您打算稍后将其放入库中,我强烈建议您不要使用 System.setOut()
  • 添加了新的 PrintStream()。 @Axel:你说得对,这种功能(重定向输入/输出/错误)不会发生在库中
  • 不幸的是,gunzip 现在抱怨格式被违反了。至少这比 EOF 更上一层楼。
【解决方案2】:

您忘记关闭信息流。只需在 while 循环后添加gout.close(); 即可使其工作:

axel@loro:~/workspace/Test/bin/tmp$ ls -l
total 12
-rw-rw-r-- 1 axel axel 1328 Oct 27 10:49 JGZip.class
axel@loro:~/workspace/Test/bin/tmp$ echo "hallo" | java JGZip > test.gz
axel@loro:~/workspace/Test/bin/tmp$ ls -l
total 24
-rw-rw-r-- 1 axel axel 1328 Oct 27 10:49 JGZip.class
-rw-rw-r-- 1 axel axel   26 Oct 27 10:49 test.gz
axel@loro:~/workspace/Test/bin/tmp$ gzip -d test.gz 
axel@loro:~/workspace/Test/bin/tmp$ ls -l
total 24
-rw-rw-r-- 1 axel axel 1328 Oct 27 10:49 JGZip.class
-rw-rw-r-- 1 axel axel    6 Oct 27 10:49 test
axel@loro:~/workspace/Test/bin/tmp$ cat test
hallo

【讨论】:

    猜你喜欢
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 2021-01-19
    • 2015-08-01
    • 2010-09-13
    • 2011-04-19
    相关资源
    最近更新 更多