问题描述
我有一个InputStream,我正在读取字符。我希望多个读者访问此InputStream。似乎一种合理的方法是将传入的数据写入StringBuffer或StringBuilder,并让多个读者读取它。不幸的是,不推荐使用StringBufferInputStream。 StringReader读取一个字符串,而不是一个不断更新的可变对象。我有什么选择?写我自己的?
I have an InputStream from which I'm reading characters. I would like multiple readers to access this InputStream. It seems that a reasonable way to achieve this is to write incoming data to a StringBuffer or StringBuilder, and have the multiple readers read that. Unfortunately, StringBufferInputStream is deprecated. StringReader reads a string, not a mutable object that's continuously being updated. What are my options? Write my own?
推荐答案
输入流的工作原理如下:一旦你读了它的一部分,就会永远消失。你不能回去重读它。你可以做的是这样的:
Input stream work like this: once you read a portion from it, it's gone forever. You can't go back and re-read it. what you could do is something like this:
class InputStreamSplitter {
InputStreamSplitter(InputStream toReadFrom) {
this.reader = new InputStreamReader(toReadFrom);
}
void addListener(Listener l) {
this.listeners.add(l);
}
void work() {
String line = this.reader.readLine();
while(line != null) {
for(Listener l : this.listeners) {
l.processLine(line);
}
}
}
}
interface Listener {
processLine(String line);
}
让所有感兴趣的人都实现Listener并将它们添加到InputStreamSplitter
have all interested parties implement Listener and add them to InputStreamSplitter
这篇关于Java中的InputStream的多个读者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!