如何在java中将String转换为InputStreamReader?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/247161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I turn a String into a InputStreamReader in java?
提问by Yossale
How can I transform a String
value into an InputStreamReader
?
如何将String
值转换为InputStreamReader
?
采纳答案by Guido
ByteArrayInputStreamalso does the trick:
ByteArrayInputStream也可以解决这个问题:
InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );
Then convert to reader:
然后转换为阅读器:
InputStreamReader reader = new InputStreamReader(is);
回答by Dan Dyer
Does it have to be specifically an InputStreamReader? How about using StringReader?
它必须是专门的 InputStreamReader 吗?如何使用StringReader?
Otherwise, you could use StringBufferInputStream, but it's deprecated because of character conversion issues (which is why you should prefer StringReader).
否则,您可以使用StringBufferInputStream,但由于字符转换问题,它已被弃用(这就是您应该更喜欢 StringReader 的原因)。
回答by toolkit
Same question as @Dan- why not StringReader ?
与@Dan相同的问题- 为什么不是 StringReader ?
If it has to be InputStreamReader, then:
如果必须是 InputStreamReader,则:
String charset = ...; // your charset
byte[] bytes = string.getBytes(charset);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
InputStreamReader isr = new InputStreamReader(bais);
回答by Yossale
I also found the apache commons IOUtils
class , so :
我还找到了 apache commonsIOUtils
类,所以:
InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));
回答by Fai Ng
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
.
您是想从 中获取 a)Reader
功能InputStreamReader
,还是 b) 中获取InputStream
功能InputStreamReader
?你不会得到 b)。 InputStreamReader
不是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.
的目的InputStreamReader
是获取一个InputStream
- 字节源 - 并将字节解码为Reader
. 您已经将数据作为字符(您的原始字符串)。将您的字符串编码为字节并将字节解码回字符将是一个多余的操作。
If you are trying to get a Reader
out of your source, use StringReader
.
如果您试图Reader
摆脱源代码,请使用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.
如果您试图获得一个InputStream
(只给您字节),请IOUtils.toInputStream(..)
按照此处其他答案的建议使用 apache commons 。