Java InputStreamReader
Is there any simple and efficient way to duplic开发者_运维问答ate an InputStreamReader?
According to the comments, wouldn't it then be better to create 1 object that reads the data and sends it to registered readers?
class Reader {
void registerReceiver(Receiver r) {
// add reciever
};
void unRegisterReceiver(Receiver r) {
// remove reciever
};
// do reading from inputstream in implementation
// and send read data to receivers
}
interface Reciever {
void receive(byte [] data);
}
The answer is that there is no general solution to this problem that is both simple and efficient ... and that always works. The root problem is that an arbitrary InputStream or Reader may deliver an indefinitely large amount of data. Certainly more data than you would want to buffer in memory. (Lots of data ==> OutOfMemoryError
.)
If you want a really simple solution, then just read the entire InputStream using an InputStreamReader and write its contents to a CharArrayWriter. Then open two (or more) CharArrayReaders ... and you've effectively duplicated the InputStream. There are two obvious problems:
- The entire stream is buffered in memory.
- The entire stream has to be read and buffered before you can hand out the Readers to consumers of the data.
To avoid using too much memory a "duplicating" InputStream / Reader needs to be able to write unread data into a temporary file, and then read back from the same file. This gets rather complicated, rather quickly. Even without the temporary file, it is still a bit tricky to implement a version that doesn't have to read the entire stream first, and that doesn't have the problem that not reading one of the Readers blocks the other one.
I suppose that you could implement this by creating two PipeInputStream
/ PipeOutputStream
pairs with a pipeSize
argument that is as large as the amount that the two Readers are likely to get out of step. But in the worst case, you need buffers big enough to hold twice the size of the stream contents ... and this approach will result in a lot of extra data copying. In other words, this approach hardly counts as efficient.
精彩评论