关于java:如何从String创建InputStream?

How does one create an InputStream from a String?

本问题已经有最佳答案,请猛点这里访问。

我不习惯使用Java中的流进行工作——我如何从EDCOX1×1中创建EDOCX1 0?


干得好:

1
InputStream is = new ByteArrayInputStream( myString.getBytes() );

多字节支持使用更新(感谢Aaron Waibel的评论):

1
InputStream is = new ByteArrayInputStream(Charset.forName("UTF-16").encode(myString).array());

请参阅Bearrayinputstream手册。

在上面的string getbytes(charset)方法中使用charset参数是安全的。

JDK 7+之后,您可以使用

1
java.nio.charset.StandardCharsets.UTF_16

而不是硬编码编码字符串:

1
InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(myString).array());


你可以这样做:

1
InputStream in = new ByteArrayInputStream(string.getBytes("UTF-8"));

注意UTF-8编码。您应该指定要将字节编码到其中的字符集。如果你不特别需要其他东西,选择UTF-8是很常见的。否则,如果您不选择任何内容,您将获得系统之间可能不同的默认编码。来自JavaDoc:

The behavior of this method when this string cannot be encoded in the default charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.


1
InputStream in = new ByteArrayInputStream(yourstring.getBytes());

Java 7 +

可以利用StandardCharsetsjdk类:

1
2
String str=...
InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(str).array());

从Java 7开始,可以使用以下习惯用法:

1
2
String someString ="...";
InputStream is = new ByteArrayInputStream( someString.getBytes(StandardCharsets.UTF_8) );

而不是charset.forname,使用来自Google的guava的com.google.common.base.charset(http://code.google.com/p/guava libraries/wiki/stringsexplained charset)稍微好一点:

1
InputStream is = new ByteArrayInputStream( myString.getBytes(Charsets.UTF_8) );

当然,您使用的字符集完全取决于您将如何处理输入流。