I need to transform a string into (finally) an InputStreamReader. Any ideas?
From stackoverflow
-
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).
-
ByteArrayInputStream also does the trick (since Java 1.4)
InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );
toolkit : should really specify the charset, to be on the safe side.slim : You might *want* to inherit the platform's default charset.Guido : Thanks. Done. What's the best way to detect the plataform's default charset ?toolkit : Charset.defaultCharset ...Michael Borgwardt : Or just use getBytes() without a parameter... Arguably it should not exist, but it will use the default encoding. -
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);
-
Cool , thank you very much. I also found the apache commons IOUtils class , so :
InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));
Joachim Sauer : Converting String->byte[] or vice versa without mentioning a character encoding is almost always a bug.McDowell : 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 -
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);
Joachim Sauer : The ".internal" should have been a hint that this is not part of any public API.D_K : yep, overlooked it, sorry.
0 comments:
Post a Comment