Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone InputStream

I'm trying to read data from an InputStream, which could either be a FileInputStream or an ObjectInputStream. In order to achieve this I'wanted to clone the stream and try to read the Object and in case of an exception convert the stream to a String using apache commons io.

    PipedInputStream in = new PipedInputStream();
    TeeInputStream tee = new TeeInputStream(stream, new PipedOutputStream(in));

    Object body;
    try {
        ObjectInput ois = new ObjectInputStream(tee);
        body = ois.readObject();
    } catch (Exception e) {
        try {
            body = IOUtils.toString(in, Charset.forName("UTF-8"));
        } catch (Exception e2) {
            throw new MarshallerException("Could not convert inputStream");
        }
    }

Unfortunately this does not work as the program waits for incoming data when trying to convert the stream in to a String.

like image 750
Jan B Avatar asked Jun 28 '14 21:06

Jan B


People also ask

Can we read InputStream twice in java?

Depending on where the InputStream is coming from, you might not be able to reset it. You can check if mark() and reset() are supported using markSupported() . If it is, you can call reset() on the InputStream to return to the beginning. If not, you need to read the InputStream from the source again.

What is the InputStream in java?

InputStream class is the superclass of all the io classes i.e. representing an input stream of bytes. It represents input stream of bytes. Applications that are defining subclass of InputStream must provide method, returning the next byte of input.


1 Answers

As already commented by Boris Spider, it is possible to read the whole stream e.g. to a byte array stream and then open new streams on that resource:

    byte[] byteArray = IOUtils.toByteArray(stream);     
    InputStream input1 = new ByteArrayInputStream(byteArray);
    InputStream input2 = new ByteArrayInputStream(byteArray);

    Object body;
    try {
        ObjectInput ois = new ObjectInputStream(input1);
        body = ois.readObject();
    } catch (Exception e) {
        try {
            body = IOUtils.toString(input2, Charset.forName("UTF-8"));
       } catch (Exception e2) {
            throw new MarshalException("Could not convert inputStream");
        }
    }
like image 184
Jan B Avatar answered Sep 18 '22 01:09

Jan B