1

正直なところ、これにはそれほど多くの問題があるべきではありませんが、明らかな何かが欠けているに違いありません。

を使用してファイルをうまく圧縮できます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);
    }
}
4

2 に答える 2

1

ストリームを閉じるのを忘れました。gout.close();while ループの後に追加するだけで機能します。

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
于 2012-10-27T08:51:14.227 に答える
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
于 2012-10-27T08:07:12.037 に答える