[英]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: 出现了几个问题:
InputOutputStream
. InputOutputStream
这样的类。 It's only InputStream
and OutputStream
and its variations (like InputDataStream
, OutputDataStream
, etc). InputStream
和OutputStream
及其变体(如InputDataStream
, OutputDataStream
等)。 Is there one? InputOutputStream
from file? InputOutputStream
? InputOutputStream
from string? InputOutputStream
? For C++ InputOutputStream
is a std::iostream
. 对于C ++,
InputOutputStream
是一个std::iostream
。 And I can convert std::fstream
or std::stringstream
to it without any problems. 我可以毫无问题地将
std::fstream
或std::stringstream
转换为它。 Is it reachable in Java? 它可以在Java中访问吗?
Thanks. 谢谢。
您可以考虑使用RandomAccessFile。
There is no InputOutputStream
in Java. Java中没有
InputOutputStream
。 If you want to DIY, follow the instructions below. 如果您想DIY,请按照以下说明操作。 If you extend an
abstract class
, use the Javadoc to ensure you override every abstract
method; 如果扩展
abstract class
,请使用Javadoc以确保覆盖每个 abstract
方法; there aren't that many. 没有那么多。
Make a class that uses two streams, an InputStream
and an OutputStream
. 创建一个使用两个流的类,一个
InputStream
和一个OutputStream
。 Extend one of the classes; 扩展其中一个类; you can't inherit from both classes (the
Stream
classes are abstract). 你不能从这两个类继承(
Stream
类是抽象的)。
Then, write each method of your InputOutputStream
in a way that calls the appropriate InputStream
or OutputStream
method. 然后,以调用相应的
InputStream
或OutputStream
方法的方式编写InputOutputStream
每个方法。
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
. 如果需要,您可以使用包装
InputOutputStream
的适配器类并扩展另一个Stream
类,将所有方法调用传递给基础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.... 但是,使用原始
InputStream
和OutputStreams
可能更容易,只需将所需的一个传递给任何使用它的方法或代码....
Hope this helped, anyway. 无论如何,希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.