maverik
maverik

Reputation: 5606

Java: common interface to InputStream and OutputStream

This question is related (in some way) with this one.

Basically, I want to make a function, like this:

public InputOutputStream func()
{
    if (condition)
    {
        // open a file stream and convert to InputOutputStream 
    }
    else
    {
        // make an InputOutputStream from string
    }
}

Several questions arise:

For C++ InputOutputStream is a std::iostream. And I can convert std::fstream or std::stringstream to it without any problems. Is it reachable in Java?

Thanks.

Upvotes: 4

Views: 1962

Answers (2)

ameed
ameed

Reputation: 1160

There is no InputOutputStream in Java. If you want to DIY, follow the instructions below. If you extend an abstract class, use the Javadoc to ensure you override every abstract method; there aren't that many.

Make a class that uses two streams, an InputStream and an OutputStream. Extend one of the classes; you can't inherit from both classes (the Stream classes are abstract).

Then, write each method of your InputOutputStream in a way that calls the appropriate InputStream or OutputStream method.

public InputOutputStream () {
    InputStream is = new BufferedInputStream(source);
    OutputStream os = new BufferedOutputStream(source);
}
//....
public int read () { return is.read(); }
public void write (int x) { os.write(x); }
//....more methods....
// (if you extend an abstract class, you must override EVERY
// abstract method in the class...)

If needed, you could use an adapter class that wraps around an InputOutputStream and extends the other Stream class, passing all method calls through to the underlying InputOutputStream.

However, it's probably easier to just use raw InputStreams and OutputStreams, though, and just pass the needed one to whatever method or code uses it....

Hope this helped, anyway.

Upvotes: 1

user207421
user207421

Reputation: 310980

You could consider using a RandomAccessFile instead.

Upvotes: 3

Related Questions