压缩输入流Java

时间:2012-10-27 08:01:38

标签: java io gzip

老实说,不应该有这么多问题,但我必须遗漏一些明显的问题。

我可以使用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);
    }
}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

你忘了关闭小溪了。只需在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