这个问题在这里已有答案:
给定一个字符串:
String exampleString = "example";
如何将其转换为 InputStream ?
InputStream
您可以使用StringReader并使用this other stackoverflow post中的解决方案将阅读器转换为输入流 .
我发现使用Apache Commons IO让我的生活变得更轻松 .
String source = "This is the source of my input stream"; InputStream in = org.apache.commons.io.IOUtils.toInputStream(source, "UTF-8");
您可能会发现该库还提供了许多其他快捷方式,可用于您可以在项目中使用的常用任务 .
像这样:
InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));
请注意,这假设您需要一个InputStream,它是一个字节流,表示编码为UTF-8的原始字符串 .
对于小于7的Java版本,请将 StandardCharsets.UTF_8 替换为 "UTF-8" .
StandardCharsets.UTF_8
"UTF-8"
3 回答
您可以使用StringReader并使用this other stackoverflow post中的解决方案将阅读器转换为输入流 .
我发现使用Apache Commons IO让我的生活变得更轻松 .
您可能会发现该库还提供了许多其他快捷方式,可用于您可以在项目中使用的常用任务 .
像这样:
请注意,这假设您需要一个InputStream,它是一个字节流,表示编码为UTF-8的原始字符串 .
对于小于7的Java版本,请将
StandardCharsets.UTF_8
替换为"UTF-8"
.