如何在 Java 中将 String 转换为 InputStream?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/782178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a String to an InputStream in Java?
提问by Iain
Given a string:
给定一个字符串:
String exampleString = "example";
How do I convert it to an InputStream
?
我如何将其转换为InputStream
?
采纳答案by Iain
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"
.
对于小于 7 的 Java 版本,替换StandardCharsets.UTF_8
为"UTF-8"
.
回答by A_M
You could use a StringReaderand convert the reader to an input stream using the solution in this other stackoverflow post.
您可以使用StringReader并使用其他 stackoverflow post 中的解决方案将读取器转换为输入流。
回答by Elijah
I find that using Apache Commons IOmakes 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.
您可能会发现该库还提供了许多其他常见任务的快捷方式,您可以在项目中使用这些快捷方式。