如何在Java中将字符串转换为InputStream? [重复]

本文翻译自: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. 您可能会发现该库还提供了许多其他快捷方式,可以在项目中使用这些常用任务。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值