flavio.donze
flavio.donze

Reputation: 8090

How to reduce writing between InputStreams and OutputStreams?

I have the following use case:

This is the code I use right now:

InputStream resourceStream = service.getStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
replace(resourceStream, output, ...);
resourceStream.close();
resourceStream = new ByteArrayInputStream(out.toByteArray());

A lot of shifting and converting streams, so I was wondering if there is a cleaner solution. Maybe some OutputStream which can be used as InputStream, or an OutputStream which contains an InputStream where the content is written to.

Upvotes: 1

Views: 159

Answers (1)

anacron
anacron

Reputation: 6711

No matter how good your idea of having a single object to write and read data from, the implementations of InputStream and OutputStream have been made as "Classes" and not "Interfaces".

Also, due to the fact that, in Java, a single subclass cannot extend multiple Super Classes, the dream of having both Input and Output stream operations in a single class remains just a dream.

That said, the only other option left for programmers would be to create a class that has both InputStream and OutputStream exposed to its clients. Something similar to what as java.net.Socket does. It exposes a getInputStream and a getOutputStream which at a logical level reads from and writes to the same "socket".

So, you can do something like this:

public class IOStreamWrapper {

    byte[] streamData;

    public InputStream getInputStream() {
        // return an inputstream that reads from streamData[]
    }

    public OutputStream getOutputStream() {
        // return an outputstream that writes to streamData[]
    }

}

References:

Java InputStream

Java OutputStream


Hope this helps!

Upvotes: 1

Related Questions