如果你有一个java.io.InputStream的对象,你应该如何处理该对象并生成一个String


假设我有一个包含文本数据的InputStream,我想将其转换为String,例如,我可以将其写入日志(log)文件.

InputStream元换成String元最简单的方法是什么?

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

推荐答案

一个很好的方法是用Apache commons101InputStream复制成StringWriter...差不多

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

甚至

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

或者,如果你不想混合使用流媒体和编剧,你可以使用ByteArrayOutputStream

Java相关问答推荐

在Java 11+中,我们可以在不编译多个文件的情况下以某种方式执行吗?

如何计算内循环的时间复杂度?

当我用OkHttpClient重写shouldInterceptRequest来发布数据时,Android WebView正在以纯HTML加载URL内容

了解Android Studio中的调试器输出

Android Studio—java—在onBindViewHolder中,将断点和空白添加到BackclerView中

无法在org. openjfx:javafx—fxml:21的下列变体之间进行 Select

@org.springframework.beans.factory.annotation.Autowired(required=true)-注入点有以下注释:-SpringBoot

JavaFX Maven Assembly插件一直打包到错误的JDK版本

我找不到&Quot;配置&的位置

为什么使用JDK21获取锁定锁比使用JDK11慢

有没有办法让扩展变得多态?

如何使用带有谓词参数的方法,而不使用lambda表达式

有没有可能在时间范围内得到多种解决方案?

是否为计划任务补偿系统睡眠?

在macOS上读取文件会导致FileNotFound,即使文件存在(并且具有权限)

如何在Java中为thunk创建映射器函数

在Java泛型中使用通配符时,如何推断类型

使用@ExceptionHandler的GlobalExceptionHandler还是来自服务器的REST应答的ResponseEntity?

如何用Micrometer&;斯普肯

ExecutorService:如果我向Executor提交了太多任务,会发生什么?