Reputation: 985
This honestly should not be having so many issues, but I must be missing something obvious.
I can compress a file just fine using GZIPOutputStream
but when I try to get the input directly (not from a file, but from a pipe or something), when I go to call gunzip -d on my file to see if it decompresses correctly, it tells me that it runs into an end of file immediately. Basically, I want these to work
echo foo | java Jgzip >foo.gz
or
java Jzip <test.txt >test.gz
And there's no guarantee these are strings, so we're reading byte by byte. I thought I could just use System.in and System.out
, but that doesn't seem to working.
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);
}
}
Upvotes: 1
Views: 1101
Reputation: 14883
I suggest:
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
Upvotes: 1
Reputation: 14169
You forgot to close the stream. Simply add gout.close();
after the while loop to make it work:
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
Upvotes: 1