Clone InputStream
Asked Answered
S

1

5

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.

Statutable answered 28/6, 2014 at 21:25 Comment(2)
No. You can read the whole stream to a known source - say a byte[] or a File and then open new streams on that source to test. You cannot create a stream twice, this simply does not work. You could try mark() and reset() but they may not be supported depending on the stream's source.Finable
According to #12107549 it should work using TeeInputStream and PipedInputStream of apache commons ioStatutable
S
8

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");
        }
    }
Statutable answered 29/6, 2014 at 10:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.