如何在 Java 中将字符串转换为 InputStream?

2022-01-12 00:00:00 string type-conversion java inputstream

给定一个字符串:

String exampleString = "example";

如何将其转换为 InputStream?

推荐答案

像这样:

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

请注意,这假设您需要一个 InputStream,它是一个字节流,表示编码为 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.

对于低于 7 的 Java 版本,将 StandardCharsets.UTF_8 替换为 "UTF-8".

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

相关文章