本文翻译自:How do I convert a String to an InputStream in Java? [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
Given a string: 给定一个字符串:
String exampleString = "example";
How do I convert it to an InputStream
? 如何将其转换为InputStream
?
#1楼
参考:https://stackoom.com/question/3HTm/如何在Java中将字符串转换为InputStream-重复
#2楼
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的版本,将StandardCharsets.UTF_8
替换为"UTF-8"
。
#3楼
您可以使用StringReader,并使用此其他stackoverflow帖子中的解决方案将阅读器转换为输入流。
#4楼
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 = org.apache.commons.io.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. 您可能会发现该库还提供了许多其他快捷方式,可以在项目中使用这些常用任务。