如何在Java中将字符串转换为InputStream ?(复制)

时间:2022-10-30 15:45:21

This question already has an answer here:

这个问题已经有了答案:

Given a string:

给定一个字符串:

String exampleString = "example";

How do I convert it to an InputStream?

如何将它转换为InputStream?

3 个解决方案

#1


1217  

Like this:

是这样的:

InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));

Note that this assumes that you want an InputStream that is a stream of bytes that represent your original string encoded as UTF-8.

注意,这假定您需要一个InputStream,它是一个字节流,表示以UTF-8编码的原始字符串。

For versions of Java less than 7, replace StandardCharsets.UTF_8 with "UTF-8".

对于Java小于7的版本,替换标准字符集。UTF_8“utf - 8”。

#2


228  

I find that using Apache Commons IO makes my life much easier.

我发现使用Apache Commons IO使我的生活更轻松。

String source = "This is the source of my input stream";
InputStream in = IOUtils.toInputStream(source, "UTF-8");

You may find that the library also offer many other shortcuts to commonly done tasks that you may be able to use in your project.

您可能会发现,该库还提供了许多其他快捷方式,用于您可以在项目中使用的常见任务。

#3


33  

You could use a StringReader and convert the reader to an input stream using the solution in this other * post.

您可以使用StringReader并使用*帖子中的解决方案将阅读器转换为输入流。

#1


1217  

Like this:

是这样的:

InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));

Note that this assumes that you want an InputStream that is a stream of bytes that represent your original string encoded as UTF-8.

注意,这假定您需要一个InputStream,它是一个字节流,表示以UTF-8编码的原始字符串。

For versions of Java less than 7, replace StandardCharsets.UTF_8 with "UTF-8".

对于Java小于7的版本,替换标准字符集。UTF_8“utf - 8”。

#2


228  

I find that using Apache Commons IO makes my life much easier.

我发现使用Apache Commons IO使我的生活更轻松。

String source = "This is the source of my input stream";
InputStream in = IOUtils.toInputStream(source, "UTF-8");

You may find that the library also offer many other shortcuts to commonly done tasks that you may be able to use in your project.

您可能会发现,该库还提供了许多其他快捷方式,用于您可以在项目中使用的常见任务。

#3


33  

You could use a StringReader and convert the reader to an input stream using the solution in this other * post.

您可以使用StringReader并使用*帖子中的解决方案将阅读器转换为输入流。