Casey Patton
Casey Patton

Reputation: 4091

GZipping from standard input to standard output in Java

Preface: I'm a total Java noob...I just wrote Hello World yesterday. Have mercy on my noob self.

I'm not sure how to read from standard input or output to standard output in Java. I know there are things like Scanners and System.out.println, but this doesn't seem to apply directly to what I'm trying to do.

In particular, I'm trying to use GZip on standard input and output the compressed result to standard output. I see that there is a GZipOutputStream class that I'll certainly want to use. However, how can I initialize the output stream to direct to std output? Further, how can I just read from standard input?

How can I accomplish this? How do I compress std input and output the result to std output?

(Here's a diagram of what I'm trying to accomplish: Std input -> GZIP (via my Java program) -> std output (the compressed version of the std input)

Upvotes: 0

Views: 593

Answers (2)

Jarek Przygódzki
Jarek Przygódzki

Reputation: 4412

import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class InToGzipOut {
    private static final int BUFFER_SIZE = 512;

    public static void main(String[] args) throws IOException {
        byte[] buf = new byte[BUFFER_SIZE];
        GZIPOutputStream out = new GZIPOutputStream(System.out);
        int len;
        while ((len = System.in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.finish();

    }
}

Upvotes: 0

mbatchkarov
mbatchkarov

Reputation: 16049

Take a look at the following constructor : GZIPInputStream(InputStream in). To get stdin as an InputStream, use System.in. Reading from the stream is done with the read(byte[] buf, int off, int len) method- take a look at the documentation for a detailed description. The whole thing would be something like

GZIPInputStream i = new GZIPInputStream(System.in);
byte[] buffer = new byte[1024];
int n = i.read(buffer, 0,buffer.length)
System.out.println("Bytes read: " + n);

Personally, I found streams in Java to have a steep learning curve, so I do recommend reading any tutorial online.

I'll leave it as an exercise to figure out the output.

-- Disclaimer: haven't actually tried the code

Upvotes: 3

Related Questions