To convert a string to a stream you need to decide which encoding the bytes in the stream should have to represent that string - for example you can: MemoryStream mStrm= new MemoryStream( Encoding. UTF8. GetBytes( contents ) );
To convert an InputStream Object int to a String using this method. Instantiate the Scanner class by passing your InputStream object as parameter. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method.
We can convert a String to an InputStream object by using the ByteArrayInputStream class. This class constructor takes the string byte array which can be done by calling the getBytes() method of a String class.
ByteArrayInputStream also does the trick:
InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );
Then convert to reader:
InputStreamReader reader = new InputStreamReader(is);
I also found the apache commons IOUtils
class , so :
InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));
Does it have to be specifically an InputStreamReader? How about using StringReader?
Otherwise, you could use StringBufferInputStream, but it's deprecated because of character conversion issues (which is why you should prefer StringReader).
Same question as @Dan - why not StringReader ?
If it has to be InputStreamReader, then:
String charset = ...; // your charset
byte[] bytes = string.getBytes(charset);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
InputStreamReader isr = new InputStreamReader(bais);
Are you trying to get a) Reader
functionality out of InputStreamReader
, or b) InputStream
functionality out of InputStreamReader
? You won't get b). InputStreamReader
is not an InputStream
.
The purpose of InputStreamReader
is to take an InputStream
- a source of bytes - and decode the bytes to chars in the form of a Reader
. You already have your data as chars (your original String). Encoding your String into bytes and decoding the bytes back to chars would be a redundant operation.
If you are trying to get a Reader
out of your source, use StringReader
.
If you are trying to get an InputStream
(which only gives you bytes), use apache commons IOUtils.toInputStream(..)
as suggested by other answers here.
You can try Cactoos:
InputStream stream = new InputStreamOf(str);
Then, if you need a Reader
:
Reader reader = new ReaderOf(stream);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With