Java String to InputStream – Java字符串到InputStream

最后修改: 2014年 6月 21日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’re going to look at how to convert a standard String to an InputStream using plain Java, Guava and the Apache Commons IO library.

在这个快速教程中,我们将看看如何使用普通的Java、Guava和Apache Commons IO库将一个标准的字符串转换成InputStream

This tutorial is part of the Java – Back to Basics series here on Baeldung.

本教程是Baeldung网站上Java -Back to Basics系列的一部分。

2. Convert With Plain Java

2.用普通的Java进行转换

Let’s start with a simple example using Java to do the conversion — using an intermediary byte array:

让我们从一个简单的例子开始,用Java来做转换–使用一个中间的byte数组。

@Test
public void givenUsingPlainJava_whenConvertingStringToInputStream_thenCorrect() 
  throws IOException {
    String initialString = "text";
    InputStream targetStream = new ByteArrayInputStream(initialString.getBytes());
}

The getBytes() method encodes this String using the platform’s default charset, so to avoid undesirable behavior, we can use getBytes(Charset charset) and control the encoding process.

getBytes()方法使用平台的默认字符集对该字符串进行编码,因此为了避免不良行为,我们可以使用getBytes(Charset charset)控制编码过程。

3. Convert With Guava

3.用番石榴转换

Guava doesn’t provide a direct conversion method but does allow us to get a CharSource out of the String and easily convert it to a ByteSource.

Guava没有提供直接的转换方法,但允许我们从String中得到一个CharSource,并轻松地将其转换成ByteSource

Then it’s easy to obtain the InputStream:

然后很容易获得InputStream

@Test
public void givenUsingGuava_whenConvertingStringToInputStream_thenCorrect() 
  throws IOException {
    String initialString = "text";
    InputStream targetStream = 
      CharSource.wrap(initialString).asByteSource(StandardCharsets.UTF_8).openStream();
}

The asByteSource method is in fact marked as @Beta. This means it can be removed in the future Guava release. We need to keep this in mind.

asByteSource方法事实上被标记为@Beta。这意味着它可以在未来的Guava版本中被移除。我们需要牢记这一点。

4. Convert With Commons IO

4.用Commons IO转换

Finally, the Apache Commons IO library provides an excellent direct solution:

最后,Apache Commons IO库提供了一个优秀的直接解决方案。

@Test
public void givenUsingCommonsIO_whenConvertingStringToInputStream_thenCorrect() 
  throws IOException {
    String initialString = "text";
    InputStream targetStream = IOUtils.toInputStream(initialString);
}

Note that we’re leaving the input stream open in these examples, so don’t forget to close it.

请注意,在这些例子中,我们让输入流处于开放状态,所以别忘了关闭它

5. Conclusion

5.总结

In this article, we presented three simple and concise ways to get an InputStream out of a simple String.

在这篇文章中,我们介绍了从一个简单的字符串中获得InputStream的三种简单而简洁的方法。

As always, the full source code is available over on GitHub.

一如既往,完整的源代码可在GitHub上获得