Clone InputStream

I am trying to read data from an InputStream, which can be either FileInputStream or ObjectInputStream. 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, because the program waits for incoming data when trying to convert a stream into a string.

+4
source share
1 answer

As Boris Spider already commented, you can read the entire stream, for example. to the byte array stream and then open new streams on this 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");
        }
    }
+5
source

Source: https://habr.com/ru/post/1546442/


All Articles