游.程 2008-11-21 16:47 采纳率: 0%
浏览 2007
已采纳

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

If you have a java.io.InputStream object, how should you process that object and produce a String?


Suppose I have an InputStream that contains text data, and I want to convert it to a String, so for example I can write that to a log file.

What is the easiest way to take the InputStream and convert it to a String?

public String convertStreamToString(InputStream is) { 
    // ???
}

转载于:https://stackoverflow.com/questions/309424/how-to-read-convert-an-inputstream-into-a-string-in-java

  • 写回答

30条回答 默认 最新

  • 关注

    A nice way to do this is using Apache commons IOUtils to copy the InputStream into a StringWriter... something like

    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, encoding);
    String theString = writer.toString();
    

    or even

    // NB: does not close inputStream, you'll have to use try-with-resources for that
    String theString = IOUtils.toString(inputStream, encoding); 
    

    Alternatively, you could use ByteArrayOutputStream if you don't want to mix your Streams and Writers

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条