How do I turn a String into a InputStreamReader in java?

JavaStringStream

Java Problem Overview


How can I transform a String value into an InputStreamReader?

Java Solutions


Solution 1 - Java

ByteArrayInputStream also does the trick:

InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );

Then convert to reader:

InputStreamReader reader = new InputStreamReader(is);

Solution 2 - Java

I also found the apache commons IOUtils class , so :

InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));

Solution 3 - Java

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).

Solution 4 - Java

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);

Solution 5 - Java

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.

Solution 6 - Java

You can try Cactoos:

InputStream stream = new InputStreamOf(str);

Then, if you need a Reader:

Reader reader = new ReaderOf(stream);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYossaleView Question on Stackoverflow
Solution 1 - JavaGuidoView Answer on Stackoverflow
Solution 2 - JavaYossaleView Answer on Stackoverflow
Solution 3 - JavaDan DyerView Answer on Stackoverflow
Solution 4 - JavatoolkitView Answer on Stackoverflow
Solution 5 - JavaFai NgView Answer on Stackoverflow
Solution 6 - Javayegor256View Answer on Stackoverflow