如何从java.lang.String获取java.io.InputStream? [英] How can I get a java.io.InputStream from a java.lang.String?
问题描述
我有一个 String
我想用作 InputStream
。在Java 1.0中,您可以使用 java.io.StringBufferInputStream
,但是 @Deprecrated
(有充分的理由 - 你不能指定字符集编码) :
I have a String
that I want to use as an InputStream
. In Java 1.0, you could use java.io.StringBufferInputStream
, but that has been @Deprecrated
(with good reason--you cannot specify the character set encoding):
此类未将
字符正确转换为字节。从JDK 1.1开始,
从字符串创建流
的首选方法是通过StringReader
类。
你可以创建一个 java.io.Reader
, java.io.StringReader
,但没有适配器可以使用一个读者
并创建一个 InputStream
。
You can create a java.io.Reader
with java.io.StringReader
, but there are no adapters to take a Reader
and create an InputStream
.
我找到了古老的错误要求合适的替代品,但不存在这样的情况 - - 据我所知。
I found an ancient bug asking for a suitable replacement, but no such thing exists--as far as I can tell.
经常建议的解决方法是使用 java.lang.String.getBytes()
作为 java.io.ByteArrayInputStream
:
The oft-suggested workaround is to use java.lang.String.getBytes()
as input to java.io.ByteArrayInputStream
:
public InputStream createInputStream(String s, String charset)
throws java.io.UnsupportedEncodingException {
return new ByteArrayInputStream(s.getBytes(charset));
}
但这意味着实现整个 String
在内存中作为一个字节数组,并且无法实现流的目的。在大多数情况下,这不是什么大问题,但我正在寻找能够保留流意图的东西 - 尽可能少的数据在内存中实现(重新)。
but that means materializing the entire String
in memory as an array of bytes, and defeats the purpose of a stream. In most cases this is not a big deal, but I was looking for something that would preserve the intent of a stream--that as little of the data as possible is (re)materialized in memory.
推荐答案
更新:这个答案正是OP不想要的。请阅读其他答案。
Update: This answer is precisely what the OP doesn't want. Please read the other answers.
对于那些我们不关心在内存中重新实现数据的情况,请使用:
For those cases when we don't care about the data being re-materialized in memory, please use:
new ByteArrayInputStream(str.getBytes("UTF-8"))
这篇关于如何从java.lang.String获取java.io.InputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!