游.程 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条)

报告相同问题?

悬赏问题

  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile