views:

13655

answers:

5

I need to transform a string into (finally) an InputStreamReader. Any ideas?

+9  A: 

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

Dan Dyer
+11  A: 

ByteArrayInputStream also does the trick (since Java 1.4)

InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );
Guido
should really specify the charset, to be on the safe side.
toolkit
You might *want* to inherit the platform's default charset.
slim
Thanks. Done. What's the best way to detect the plataform's default charset ?
Guido
Charset.defaultCharset ...
toolkit
Or just use getBytes() without a parameter... Arguably it should not exist, but it will use the default encoding.
Michael Borgwardt
+7  A: 

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);
toolkit
+4  A: 

Cool , thank you very much. I also found the apache commons IOUtils class , so :

InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));
yossale
Converting String->byte[] or vice versa without mentioning a character encoding is almost always a bug.
Joachim Sauer
This may cause data loss, depending on the default platform encoding and characters in the string. Specifying a Unicode encoding for both encoding and decoding operations would be better. Read this for more details: http://illegalargumentexception.blogspot.com/2009/05/java-rough-guide-to-character-encoding.html#javaencoding_lossyconversions
McDowell
A: 

Hi,

If you know that the String is in UTF-8 you could use alternatively:

InputStream is = com.sun.xml.internal.ws.util.xml.XmlUtil.getUTF8Stream(myString);

D_K
The ".internal" should have been a hint that this is not part of any public API.
Joachim Sauer
yep, overlooked it, sorry.
D_K