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

如何在Java中将InputStream读取/转换为字符串?,java,string,io,stream,inputstream,Java,String,Io,Stream,Inputstream,如果您有一个java.io.InputStream对象,您应该如何处理该对象并生成一个字符串 假设我有一个包含文本数据的InputStream,我想将其转换为字符串,例如,我可以将其写入日志文件 获取InputStream并将其转换为字符串的最简单方法是什么 一个很好的方法是使用将InputStream复制到StringWriter中。。。差不多 StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer,

如果您有一个java.io.InputStream对象,您应该如何处理该对象并生成一个字符串

假设我有一个包含文本数据的InputStream,我想将其转换为字符串,例如,我可以将其写入日志文件

获取InputStream并将其转换为字符串的最简单方法是什么


一个很好的方法是使用将InputStream复制到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.io.Reader实例。然后可以将其读取并添加到StringBuilder中。如果不在多个线程中访问StringBuffer,则不需要StringBuffer,而且StringBuilder速度更快。这里的诀窍是我们在块中工作,因此不需要其他缓冲流。块大小是参数化的,用于运行时性能优化

public static String slurp(final InputStream is, final int bufferSize) {
    final char[] buffer = new char[bufferSize];
    final StringBuilder out = new StringBuilder();
    try (Reader in = new InputStreamReader(is, "UTF-8")) {
        for (;;) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
    }
    catch (UnsupportedEncodingException ex) {
        /* ... */
    }
    catch (IOException ex) {
        /* ... */
    }
    return out.toString();
}
Apache Commons允许:

String myString = IOUtils.toString(myInputStream, "UTF-8");
当然,您可以选择UTF-8之外的其他字符编码

另请参见:

使用:

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;

public static String readInputStreamAsString(InputStream in)
    throws IOException {

    BufferedInputStream bis = new BufferedInputStream(in);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    int result = bis.read();
    while(result != -1) {
      byte b = (byte)result;
      buf.write(b);
      result = bis.read();
    }
    return buf.toString();
}
InputStream in = /* Your InputStream */;
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String read;

while ((read=br.readLine()) != null) {
    //System.out.println(read);
    sb.append(read);
}

br.close();
return sb.toString();

如果不能使用Commons IO FileUtils/IOUtils/CopyUtils,下面是一个使用BufferedReader逐行读取文件的示例:

public class StringFromFile {
    public static void main(String[] args) /*throws UnsupportedEncodingException*/ {
        InputStream is = StringFromFile.class.getResourceAsStream("file.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(is/*, "UTF-8"*/));
        final int CHARS_PER_PAGE = 5000; //counting spaces
        StringBuilder builder = new StringBuilder(CHARS_PER_PAGE);
        try {
            for(String line=br.readLine(); line!=null; line=br.readLine()) {
                builder.append(line);
                builder.append('\n');
            }
        } 
        catch (IOException ignore) { }

        String text = builder.toString();
        System.out.println(text);
    }
}
或者,如果您想要原始速度,我会根据Paul de Vrieze的建议提出一个变体,以避免使用内部使用StringBuffer的StringWriter:

public class StringFromFileFast {
    public static void main(String[] args) /*throws UnsupportedEncodingException*/ {
        InputStream is = StringFromFileFast.class.getResourceAsStream("file.txt");
        InputStreamReader input = new InputStreamReader(is/*, "UTF-8"*/);
        final int CHARS_PER_PAGE = 5000; //counting spaces
        final char[] buffer = new char[CHARS_PER_PAGE];
        StringBuilder output = new StringBuilder(CHARS_PER_PAGE);
        try {
            for(int read = input.read(buffer, 0, buffer.length);
                    read != -1;
                    read = input.read(buffer, 0, buffer.length)) {
                output.append(buffer, 0, read);
            }
        } catch (IOException ignore) { }

        String text = output.toString();
        System.out.println(text);
    }
}

如果您使用Google Collections/Guava,您可以执行以下操作:

InputStream stream = ...
String content = CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8));
Closeables.closeQuietly(stream);

请注意,InputStreamReader的第二个参数,即Charsets.UTF_8不是必需的,但如果您知道应该使用哪种编码,则通常最好指定该编码

这里有一种只使用标准Java库的方法。请注意,流没有关闭,您的里程可能会有所不同

static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}
我从这篇文章中学到了这个技巧。它工作的原因是迭代流中的令牌,在这种情况下,我们使用输入边界的开头\A来分离令牌,从而为流的整个内容只提供一个令牌

注意,如果需要具体说明输入流的编码,可以向Scanner构造函数提供第二个参数,该参数指示要使用的字符集,例如UTF-8

“帽子提示”同样适用于曾向我指出上述文章的作者。

使用:

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;

public static String readInputStreamAsString(InputStream in)
    throws IOException {

    BufferedInputStream bis = new BufferedInputStream(in);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    int result = bis.read();
    while(result != -1) {
      byte b = (byte)result;
      buf.write(b);
      result = bis.read();
    }
    return buf.toString();
}
InputStream in = /* Your InputStream */;
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String read;

while ((read=br.readLine()) != null) {
    //System.out.println(read);
    sb.append(read);
}

br.close();
return sb.toString();

我做了一些计时测试,因为时间总是很重要的

我试图以3种不同的方式将响应转换为字符串。如下所示 为了可读性,我省略了try/catch块

为了提供上下文,这是所有3种方法的前面代码:

一,

二,

三,

因此,在使用相同的请求/响应数据对每种方法运行500个测试之后,下面是数字。再一次,这些是我的发现,你们的发现可能并不完全相同,但我写这篇文章是为了给其他人一些关于这些方法效率差异的指示

排名: 方法1 接近3-比1慢2.6% 方法2-比1慢4.3%


这些方法中的任何一种都是获取响应并从中创建字符串的合适解决方案。

如果您喜欢冒险,您可以将Scala和Java混合使用,最终得到以下结果:

scala.io.Source.fromInputStream(is).mkString("")
混合使用Java和Scala代码和库有其好处


请参阅此处的完整描述:

这里或多或少是sampath的答案,稍作澄清并表示为一个函数:

String streamToString(InputStream in) throws IOException {
  StringBuilder out = new StringBuilder();
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  for(String line = br.readLine(); line != null; line = br.readLine()) 
    out.append(line);
  br.close();
  return out.toString();
}

这是最适合Android和任何其他JVM的纯Java解决方案

这个解决方案非常有效。。。它简单、快速,同样适用于大小流!!见上面的基准。。第八号


下面是如何使用JDK和字节数组缓冲区来实现这一点。这实际上就是commons io IOUtils.copy方法的工作方式。如果从读取器而不是InputStream复制,则可以将byte[]替换为char[]


如果使用流读取器,请确保在末尾关闭流

private String readStream(InputStream iStream) throws IOException {
    //build a Stream Reader, it can read char by char
    InputStreamReader iStreamReader = new InputStreamReader(iStream);
    //build a buffered Reader, so that i can read whole line at once
    BufferedReader bReader = new BufferedReader(iStreamReader);
    String line = null;
    StringBuilder builder = new StringBuilder();
    while((line = bReader.readLine()) != null) {  //Read till end
        builder.append(line);
        builder.append("\n"); // append new line to preserve lines
    }
    bReader.close();         //close all opened stuff
    iStreamReader.close();
    //iStream.close(); //EDIT: Let the creator of the stream close it!
                       // some readers may auto close the inner stream
    return builder.toString();
}
编辑:在JDK 7+上,可以使用try with resources构造

/**
 * Reads the stream into a string
 * @param iStream the input stream
 * @return the string read from the stream
 * @throws IOException when an IO error occurs
 */
private String readStream(InputStream iStream) throws IOException {

    //Buffered reader allows us to read line by line
    try (BufferedReader bReader =
                 new BufferedReader(new InputStreamReader(iStream))){
        StringBuilder builder = new StringBuilder();
        String line;
        while((line = bReader.readLine()) != null) {  //Read till end
            builder.append(line);
            builder.append("\n"); // append new line to preserve lines
        }
        return builder.toString();
    }
}

下面是我经过一些实验后提出的最优雅、最纯粹的Java无库解决方案:

public static String fromStream(InputStream in) throws IOException
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder out = new StringBuilder();
    String newLine = System.getProperty("line.separator");
    String line;
    while ((line = reader.readLine()) != null) {
        out.append(line);
        out.append(newLine);
    }
    return out.toString();
}

以下是在不使用任何第三方库的情况下将InputStream转换为字符串的完整方法。对单线程环境使用StringBuilder,否则使用StringBuffer


这个很好,因为:

它安全地处理字符集。 您可以控制读取缓冲区的大小。 您可以设置生成器的长度,而不必是精确的值。 没有库依赖关系。 适用于Java 7或更高版本。 怎么做

对于JDK9

public static String inputStreamString(InputStream inputStream) throws IOException {
    try (inputStream) {
        return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
    }
}

我会使用一些Java8技巧

public static String streamToString(final InputStream inputStream) throws Exception {
    // buffering optional
    try
    (
        final BufferedReader br
           = new BufferedReader(new InputStreamReader(inputStream))
    ) {
        // parallel optional
        return br.lines().parallel().collect(Collectors.joining("\n"));
    } catch (final IOException e) {
        throw new RuntimeException(e);
        // whatever.
    }
}

基本上与其他一些答案相同,只是更加简洁。

这是一个改编自org.apache.commons.io.IOUtils的答案,适用于那些希望使用apache实现但不想要整个库的人

private static final int BUFFER_SIZE = 4 * 1024;

public static String inputStreamToString(InputStream inputStream, String charsetName)
        throws IOException {
    StringBuilder builder = new StringBuilder();
    InputStreamReader reader = new InputStreamReader(inputStream, charsetName);
    char[] buffer = new char[BUFFER_SIZE];
    int length;
    while ((length = reader.read(buffer)) != -1) {
        builder.append(buffer, 0, length);
    }
    return builder.toString();
}

Kotlin用户只需执行以下操作:

println(InputStreamReader(is).readText())
鉴于

readText()
是Kotlin标准库的内置扩展方法 使用s的纯Java解决方案,从Java8开始工作

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

// ...
public static String inputStreamToString(InputStream is) throws IOException {
    try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
        return br.lines().collect(Collectors.joining(System.lineSeparator()));
    }
}
正如Christoffe Hammarström在下文中提到的,更安全的做法是明确指定。也就是说,InputStreamReader构造函数可以进行如下更改:

new InputStreamReader(is, Charset.forName("UTF-8"))
下面是我基于Java 8的解决方案,它使用新的Stream API收集InputStream中的所有行:

为了完整起见,这里是Java 9解决方案:

public static String toString(InputStream input) throws IOException {
    return new String(input.readAllBytes(), StandardCharsets.UTF_8);
}
这使用了添加到Java 9中的方法。

在reduce方面,它可以用Java 8表示为:

String fromFile = new BufferedReader(new   
InputStreamReader(inputStream)).lines().reduce(String::concat).get();
使用Java 9中支持的和采用字符集名称的:

public static String gobble(InputStream in, String charsetName) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    in.transferTo(bos);
    return bos.toString(charsetName);
}

总结我找到的11种主要方法的其他答案,见下文。我编写了一些性能测试,请参见下面的结果:

将InputStream转换为字符串的方法:

使用IOUtils.toString Apache Utils

 String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
用番石榴

使用scannerjdk

使用流API Java8。警告:此解决方案将不同的换行符\r\n转换为\r\n

使用并行流API Java8。警告:此解决方案将不同的换行符\r\n转换为\r\n

使用InputStreamReader和StringBuilder JDK

使用StringWriter和IOUtils.copy Apache Commons

 StringWriter writer = new StringWriter();
 IOUtils.copy(inputStream, writer, "UTF-8");
 return writer.toString();
使用ByteArrayOutputStream和inputStream.read JDK

使用BufferedReaderJDK。警告:此解决方案将不同的换行符(如\n\r)转换为line.separator系统属性(例如,在Windows中)转换为\r\n

 String newLine = System.getProperty("line.separator");
 BufferedReader reader = new BufferedReader(
         new InputStreamReader(inputStream));
 StringBuilder result = new StringBuilder();
 for (String line; (line = reader.readLine()) != null; ) {
     if (result.length() > 0) {
         result.append(newLine);
     }
     result.append(line);
 }
 return result.toString();
使用BufferedInputStream和ByteArrayOutputStream JDK

使用inputStream.read和StringBuilder JDK。警告:此解决方案存在Unicode问题,例如,俄语文本仅适用于非Unicode文本

StringBuilder sb = new StringBuilder();
for (int ch; (ch = inputStream.read()) != -1; ) {
    sb.append((char) ch);
}
return sb.toString();
警告:

解决方案4、5和9将不同的换行符转换为一个换行符

解决方案11无法正确使用Unicode文本

StringBuilder sb = new StringBuilder();
for (int ch; (ch = inputStream.read()) != -1; ) {
    sb.append((char) ch);
}
return sb.toString();
性能测试

对于小字符串长度=175、模式中的url=平均时间、系统=Linux、分数1343的性能测试是最好的:

基准模式Cnt分数误差单位 8.ByteArrayOutputStream和读取JDK avgt 10 1343±0028 us/op 6.InputStreamReader和StringBuilder JDK avgt 10 6980±0404 us/op 10缓冲的数据流,通过TEARRAYOUTPUTSTREAM avgt 10 7437±0735 us/op 11InputStream.read和StringBuilder JDK avgt 10 8977±0328 us/op 7.StringWriter和IOUtils.copy Apache avgt 10 10613±0599 us/op 1.IOUtils.toString Apache Utils avgt 10 10605±0527 us/op 3.扫描仪JDK avgt 10 12083±0293 us/op 2.CharStreams番石榴avgt 10 12999±0514 us/op 4.流Api Java 8 avgt 10 15811±0605 us/op 9缓冲读取器JDK avgt 10 16038±0711 us/op 5.并行流Api Java 8 avgt 10 21544±0583 us/op 对于大字符串长度=50100,模式中的url=平均时间,系统=Linux,分数200715的性能测试是最好的:

基准模式Cnt分数误差单位 8.ByteArrayOutputStream和读取JDK avgt 10 200715±18103 us/op 1.IOUtils.toString Apache Utils avgt 10 300019±8751 us/op 6.InputStreamReader和StringBuilder JDK avgt 10 347616±130348 us/op 7.StringWriter和IOUtils.copy Apache avgt 10 352791±105337 us/op 2.CharStreams番石榴avgt 10 420137±59877 us/op 9BufferedReader JDK avgt 10 632028±17002 us/op 5.并行流Api Java 8 avgt 10 662999±46199 us/op 4.流Api Java 8 avgt 10 701269±82296 us/op 10缓冲输入流,按TEARRAYOUTPUTSTREAM avgt 10 740837±5613 us/op 3.扫描仪JDK avgt 10 751417±62026 us/op 11InputStream.read和StringBuilder JDK avgt 10 2919350±1101942 us/op 在Windows 7系统中,根据输入流长度绘制性能测试图

性能测试平均时间取决于Windows 7系统中的输入流长度:

长度182 546 1092 3276 9828 29484 58968 测试8 0.38 0.938 1.868 4.448 13.412 36.459 72.708 测试4 2.362 3.609 5.573 12.769 40.74 81.415 159.864 测试5 3.881 5.075 6.904 14.123 50.258 129.937 166.162 测试9 2.237 3.493 5.422 11.977 45.98 89.336 177.39 测试6 1.261 2.12 4.38 10.698 31.821 86.106 186.636 测试7 1.601 2.391 3.646 8.367 38.196 110.221 211.016 测试1 1.529 2.381 3.527 8.411 40.551 105.16 212.573 测试3 3.035 3.934 8.606 20.858 61.571 118.744 235.428 测试2 3.136 6.238 10.508 33.48 43.532 118.044 239.481 测试10 1.593 4.736 7.527 20.557 59.856 162.907 323.147 测试11 3.913 11.506 23.26 68.644 207.591 600.444 1211.545 阿诺特 r one,对于所有Spring用户:

导入java.nio.charset.StandardCharset; 导入org.springframework.util.FileCopyUtils; 公共字符串convertStreamToStringInputStream为IOException{ 返回新的StringFileCopyUtils.CopyToByTerrayis,StandardCharsets.UTF_8; }
org.springframework.util.StreamUtils中的实用程序方法与FileCopyUtils中的类似,但它们在完成后保持流打开。

JDK中最简单的方法是使用以下代码片段

String convertToString(InputStream in){
    String resource = new Scanner(in).useDelimiter("\\Z").next();
    return resource;
}

我在这里做了14个不同答案的基准测试,很抱歉没有提供学分,但是重复的太多了

结果非常令人惊讶。事实证明,Apache IOUtils是最慢的,ByteArrayOutputStream是最快的解决方案:

首先,这里是最好的方法:

public String inputStreamToString(InputStream inputStream) throws IOException {
    try(ByteArrayOutputStream result = new ByteArrayOutputStream()) {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }

        return result.toString(UTF_8);
    }
}
基准测试结果,20个周期内20 MB随机字节 以毫秒为单位的时间

ByteArrayOutputStreamTest:194 NioStream:198 Java9ISTransferTo:201 Java9ISReadAllBytes:205 BufferedInputStreamVsByteArrayOutputStream:314 ApachistringWriter2:574 瓜瓦卡海峡:589 ScannerReaderOnextTest:614 扫描阅读器:633 作者:1544 StreamApi:错误 ParallelStreamApi:错误 BufferReaderTest:错误 InputStreamAndStringBuilder:错误 基准源代码 纯Java标准库解决方案-无库 自Java 10以来- 无环解 没有新行字符处理
特别是因为准时制。在阅读了基准源代码之后,我确信上面的这些值并不精确,每个人都应该小心相信它们。@Dalibor您可能应该为您的声明提供更多的理由,而不仅仅是一个链接。我认为这是一个众所周知的事实,即创建自己的基准并不容易。对于那些不知道这一点的人来说,这是有联系的@Dalibor我可能不是最好的,但是我对Java基准有很好的理解,所以除非你能指出一个具体的问题,否则你只是在误导,在那种情况下我不会继续与你的对话。我基本上同意Dalibor。您说您对Java基准测试有很好的理解,但您似乎实现了最简单的方法,但显然不知道这种方法的众所周知的问题。首先,阅读关于这个问题的每一篇文章:toString是否被弃用了?我看到IOUtils.convertstreamtostrignice工作了。可能有助于提供tl;下面是dr summary,也就是说,扔掉那些在换行符/unicode方面有问题的解决方案,然后扔掉那些仍然说有或没有外部库最快的解决方案。这个答案似乎是不完整的。我对发布这个答案后添加的Java 9 InputStream.transferTo和Java 10 Reader.transferTo解决方案感到好奇,因此,我检查了链接代码并为它们添加了基准。我只测试了大字符串基准。InputStream.transferTo是所有测试的解决方案中速度最快的,与我的机器上的test8一样,运行时间占60%。Reader.transferTo比test8慢,但比所有其他测试都快。这就是说,它在95%的时间内作为test1运行,所以这不是一个显著的改进。我在本文的编辑中将所有while循环转换为for循环,以避免在循环之外使用的变量污染名称空间。这是一个适用于大多数Java读写器循环的巧妙技巧。所以新的StringinputStream.readAllBytes使用String的byte[]构造函数工作。这是否回答了您的问题?请记住,您需要考虑输入流的编码。系统默认值不一定总是您想要的。t这些答案大部分是在Java 9之前编写的,但是现在您可以使用.readAllBytes从InputStream获取字节数组。因此,简单地说,new StringinputStream.readAllBytes使用String的byte[]构造函数工作。我们不应该在返回值之前关闭扫描仪吗?@OlegMarkelov可能。我对其进行了基准测试,发现这是我机器上最快的解决方案,运行时间约为下一个最快解决方案基准测试时间的60%。试图恢复InputStream,不工作的readLine将删除换行符,因此生成的字符串将不包含换行符,除非在添加到生成器的每一行之间添加行分隔符。
public static String gobble(InputStream in, String charsetName) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    in.transferTo(bos);
    return bos.toString(charsetName);
}
 String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
 String result = CharStreams.toString(new InputStreamReader(
       inputStream, Charsets.UTF_8));
 Scanner s = new Scanner(inputStream).useDelimiter("\\A");
 String result = s.hasNext() ? s.next() : "";
 String result = new BufferedReader(new InputStreamReader(inputStream))
   .lines().collect(Collectors.joining("\n"));
 String result = new BufferedReader(new InputStreamReader(inputStream))
    .lines().parallel().collect(Collectors.joining("\n"));
 int bufferSize = 1024;
 char[] buffer = new char[bufferSize];
 StringBuilder out = new StringBuilder();
 Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8);
 for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0; ) {
     out.append(buffer, 0, numRead);
 }
 return out.toString();
 StringWriter writer = new StringWriter();
 IOUtils.copy(inputStream, writer, "UTF-8");
 return writer.toString();
 ByteArrayOutputStream result = new ByteArrayOutputStream();
 byte[] buffer = new byte[1024];
 for (int length; (length = inputStream.read(buffer)) != -1; ) {
     result.write(buffer, 0, length);
 }
 // StandardCharsets.UTF_8.name() > JDK 7
 return result.toString("UTF-8");
 String newLine = System.getProperty("line.separator");
 BufferedReader reader = new BufferedReader(
         new InputStreamReader(inputStream));
 StringBuilder result = new StringBuilder();
 for (String line; (line = reader.readLine()) != null; ) {
     if (result.length() > 0) {
         result.append(newLine);
     }
     result.append(line);
 }
 return result.toString();
BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
for (int result = bis.read(); result != -1; result = bis.read()) {
    buf.write((byte) result);
}
// StandardCharsets.UTF_8.name() > JDK 7
return buf.toString("UTF-8");
StringBuilder sb = new StringBuilder();
for (int ch; (ch = inputStream.read()) != -1; ) {
    sb.append((char) ch);
}
return sb.toString();
String convertToString(InputStream in){
    String resource = new Scanner(in).useDelimiter("\\Z").next();
    return resource;
}
public String inputStreamToString(InputStream inputStream) throws IOException {
    try(ByteArrayOutputStream result = new ByteArrayOutputStream()) {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }

        return result.toString(UTF_8);
    }
}
import com.google.common.io.CharStreams;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * Created by Ilya Gazman on 2/13/18.
 */
public class InputStreamToString {


    private static final String UTF_8 = "UTF-8";

    public static void main(String... args) {
        log("App started");
        byte[] bytes = new byte[1024 * 1024];
        new Random().nextBytes(bytes);
        log("Stream is ready\n");

        try {
            test(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void test(byte[] bytes) throws IOException {
        List<Stringify> tests = Arrays.asList(
                new ApacheStringWriter(),
                new ApacheStringWriter2(),
                new NioStream(),
                new ScannerReader(),
                new ScannerReaderNoNextTest(),
                new GuavaCharStreams(),
                new StreamApi(),
                new ParallelStreamApi(),
                new ByteArrayOutputStreamTest(),
                new BufferReaderTest(),
                new BufferedInputStreamVsByteArrayOutputStream(),
                new InputStreamAndStringBuilder(),
                new Java9ISTransferTo(),
                new Java9ISReadAllBytes()
        );

        String solution = new String(bytes, "UTF-8");

        for (Stringify test : tests) {
            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {
                String s = test.inputStreamToString(inputStream);
                if (!s.equals(solution)) {
                    log(test.name() + ": Error");
                    continue;
                }
            }
            long startTime = System.currentTimeMillis();
            for (int i = 0; i < 20; i++) {
                try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {
                    test.inputStreamToString(inputStream);
                }
            }
            log(test.name() + ": " + (System.currentTimeMillis() - startTime));
        }
    }

    private static void log(String message) {
        System.out.println(message);
    }

    interface Stringify {
        String inputStreamToString(InputStream inputStream) throws IOException;

        default String name() {
            return this.getClass().getSimpleName();
        }
    }

    static class ApacheStringWriter implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            StringWriter writer = new StringWriter();
            IOUtils.copy(inputStream, writer, UTF_8);
            return writer.toString();
        }
    }

    static class ApacheStringWriter2 implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            return IOUtils.toString(inputStream, UTF_8);
        }
    }

    static class NioStream implements Stringify {

        @Override
        public String inputStreamToString(InputStream in) throws IOException {
            ReadableByteChannel channel = Channels.newChannel(in);
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 16);
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            WritableByteChannel outChannel = Channels.newChannel(bout);
            while (channel.read(byteBuffer) > 0 || byteBuffer.position() > 0) {
                byteBuffer.flip();  //make buffer ready for write
                outChannel.write(byteBuffer);
                byteBuffer.compact(); //make buffer ready for reading
            }
            channel.close();
            outChannel.close();
            return bout.toString(UTF_8);
        }
    }

    static class ScannerReader implements Stringify {

        @Override
        public String inputStreamToString(InputStream is) throws IOException {
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            return s.hasNext() ? s.next() : "";
        }
    }

    static class ScannerReaderNoNextTest implements Stringify {

        @Override
        public String inputStreamToString(InputStream is) throws IOException {
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            return s.next();
        }
    }

    static class GuavaCharStreams implements Stringify {

        @Override
        public String inputStreamToString(InputStream is) throws IOException {
            return CharStreams.toString(new InputStreamReader(
                    is, UTF_8));
        }
    }

    static class StreamApi implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            return new BufferedReader(new InputStreamReader(inputStream))
                    .lines().collect(Collectors.joining("\n"));
        }
    }

    static class ParallelStreamApi implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            return new BufferedReader(new InputStreamReader(inputStream)).lines()
                    .parallel().collect(Collectors.joining("\n"));
        }
    }

    static class ByteArrayOutputStreamTest implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            try(ByteArrayOutputStream result = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) != -1) {
                    result.write(buffer, 0, length);
                }

                return result.toString(UTF_8);
            }
        }
    }

    static class BufferReaderTest implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            String newLine = System.getProperty("line.separator");
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder result = new StringBuilder(UTF_8);
            String line;
            boolean flag = false;
            while ((line = reader.readLine()) != null) {
                result.append(flag ? newLine : "").append(line);
                flag = true;
            }
            return result.toString();
        }
    }

    static class BufferedInputStreamVsByteArrayOutputStream implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            ByteArrayOutputStream buf = new ByteArrayOutputStream();
            int result = bis.read();
            while (result != -1) {
                buf.write((byte) result);
                result = bis.read();
            }

            return buf.toString(UTF_8);
        }
    }

    static class InputStreamAndStringBuilder implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            int ch;
            StringBuilder sb = new StringBuilder(UTF_8);
            while ((ch = inputStream.read()) != -1)
                sb.append((char) ch);
            return sb.toString();
        }
    }

    static class Java9ISTransferTo implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            inputStream.transferTo(bos);
            return bos.toString(UTF_8);
        }
    }

    static class Java9ISReadAllBytes implements Stringify {

        @Override
        public String inputStreamToString(InputStream inputStream) throws IOException {
            return new String(inputStream.readAllBytes(), UTF_8);
        }
    }

}
String inputStreamToString(InputStream inputStream, Charset charset) throws IOException {
    try (
            final StringWriter writer = new StringWriter();
            final InputStreamReader reader = new InputStreamReader(inputStream, charset)
        ) {
        reader.transferTo(writer);
        return writer.toString();
    }
}