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
2008-10-29 15:08:33
+11
A:
ByteArrayInputStream also does the trick (since Java 1.4)
InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );
Guido
2008-10-29 15:12:11
should really specify the charset, to be on the safe side.
toolkit
2008-10-29 15:14:21
You might *want* to inherit the platform's default charset.
slim
2008-10-29 15:21:58
Thanks. Done. What's the best way to detect the plataform's default charset ?
Guido
2008-10-29 16:14:56
Charset.defaultCharset ...
toolkit
2008-10-29 16:32:00
Or just use getBytes() without a parameter... Arguably it should not exist, but it will use the default encoding.
Michael Borgwardt
2009-08-11 15:34:16
+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
2008-10-29 15:13:20
+4
A:
Cool , thank you very much. I also found the apache commons IOUtils class , so :
InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));
yossale
2008-10-29 15:52:59
Converting String->byte[] or vice versa without mentioning a character encoding is almost always a bug.
Joachim Sauer
2009-08-11 15:31:12
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
2009-08-11 15:44:03
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
2009-08-11 15:25:28
The ".internal" should have been a hint that this is not part of any public API.
Joachim Sauer
2009-08-11 15:31:45