Convert BufferedReader to InputStream

2019-08-05 06:37发布

问题:

I have an API with a useful method that requires an InputStream argument. The data that I want to provide to this method is currently represented by a BufferedReader. The library is prepared to deal with byte streams, I have character data that I'm going to feed it.

I am not changing between different encodings.

I have spent what seems an inordinate amount of time trying to discover what I was sure would be a standard way to do this, but there doesn't seem to be one. I do NOT want to read all my data into memory, so a byte array input stream is out.

I suppose I can write one myself -- the read to my input stream would call readLine (or just read of a buffer) to get some bytes and then return an encoded array of bytes from it. But do I have to? Hasn't someone else already done all the calculations and error checking and all of that nonsense that is hard to get right the first time?

回答1:

Judging by your title ReaderInputStream from appache commons-io may interest you.