Reputation: 5606
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:
InputOutputStream
. It's only InputStream
and OutputStream
and its variations (like InputDataStream
, OutputDataStream
, etc). Is there one? I need a stream which supports both read and write operations.InputOutputStream
from file?InputOutputStream
from string?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
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 InputStream
s and OutputStreams
, though, and just pass the needed one to whatever method or code uses it....
Hope this helped, anyway.
Upvotes: 1