如何在Java中读取/转换输入流作为字符串?

2022-08-31 01:22:20

如果你有一个对象,你应该如何处理这个对象并生成一个?java.io.InputStreamString


假设我有一个包含文本数据的,并且我想将其转换为 ,因此例如,我可以将其写入日志文件。InputStreamString

获取并将其转换为 ?InputStreamString

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

答案 1

总结我发现的其他答案 11 主要方法(见下文)。我写了一些性能测试(见下面的结果):

将输入流转换为字符串的方法:

  1. Using (Apache Utils)IOUtils.toString

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

     String result = CharStreams.toString(new InputStreamReader(
           inputStream, Charsets.UTF_8));
    
  3. 使用 (JDK)Scanner

     Scanner s = new Scanner(inputStream).useDelimiter("\\A");
     String result = s.hasNext() ? s.next() : "";
    
  4. 使用 Stream API (Java 8)。警告:此解决方案将不同的换行符(如 )转换为 。\r\n\n

     String result = new BufferedReader(new InputStreamReader(inputStream))
       .lines().collect(Collectors.joining("\n"));
    
  5. 使用并行流 API (Java 8)。警告:此解决方案将不同的换行符(如 )转换为 。\r\n\n

     String result = new BufferedReader(new InputStreamReader(inputStream))
        .lines().parallel().collect(Collectors.joining("\n"));
    
  6. 使用和 (JDK)InputStreamReaderStringBuilder

     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();
    
  7. 使用和(Apache Commons)StringWriterIOUtils.copy

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

     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");
    
  9. 使用 (JDK)。警告:此解决方案将不同的换行符(如)转换为系统属性(例如,在 Windows 中转换为“\r\n”)。BufferedReader\n\rline.separator

     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();
    
  10. 使用和 (JDK)BufferedInputStreamByteArrayOutputStream

    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");
    
  11. 使用和 (JDK)。警告:此解决方案在 Unicode 方面存在问题,例如俄语文本(仅适用于非 Unicode 文本)inputStream.read()StringBuilder

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

警告

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

  2. 解决方案 11 无法正确处理 Unicode 文本

性能测试

小(长度 = 175),github 中的 url 的性能测试(模式 = 平均时间,系统 = Linux,得分 1,343 是最好的):String

              Benchmark                         Mode  Cnt   Score   Error  Units
 8. ByteArrayOutputStream and read (JDK)        avgt   10   1,343 ± 0,028  us/op
 6. InputStreamReader and StringBuilder (JDK)   avgt   10   6,980 ± 0,404  us/op
10. BufferedInputStream, ByteArrayOutputStream  avgt   10   7,437 ± 0,735  us/op
11. InputStream.read() and StringBuilder (JDK)  avgt   10   8,977 ± 0,328  us/op
 7. StringWriter and IOUtils.copy (Apache)      avgt   10  10,613 ± 0,599  us/op
 1. IOUtils.toString (Apache Utils)             avgt   10  10,605 ± 0,527  us/op
 3. Scanner (JDK)                               avgt   10  12,083 ± 0,293  us/op
 2. CharStreams (guava)                         avgt   10  12,999 ± 0,514  us/op
 4. Stream Api (Java 8)                         avgt   10  15,811 ± 0,605  us/op
 9. BufferedReader (JDK)                        avgt   10  16,038 ± 0,711  us/op
 5. parallel Stream Api (Java 8)                avgt   10  21,544 ± 0,583  us/op

大的性能测试(长度 = 50100),github 中的 url(模式 = 平均时间,系统 = Linux,得分 200,715 是最好的):String

               Benchmark                        Mode  Cnt   Score        Error  Units
 8. ByteArrayOutputStream and read (JDK)        avgt   10   200,715 ±   18,103  us/op
 1. IOUtils.toString (Apache Utils)             avgt   10   300,019 ±    8,751  us/op
 6. InputStreamReader and StringBuilder (JDK)   avgt   10   347,616 ±  130,348  us/op
 7. StringWriter and IOUtils.copy (Apache)      avgt   10   352,791 ±  105,337  us/op
 2. CharStreams (guava)                         avgt   10   420,137 ±   59,877  us/op
 9. BufferedReader (JDK)                        avgt   10   632,028 ±   17,002  us/op
 5. parallel Stream Api (Java 8)                avgt   10   662,999 ±   46,199  us/op
 4. Stream Api (Java 8)                         avgt   10   701,269 ±   82,296  us/op
10. BufferedInputStream, ByteArrayOutputStream  avgt   10   740,837 ±    5,613  us/op
 3. Scanner (JDK)                               avgt   10   751,417 ±   62,026  us/op
11. InputStream.read() and StringBuilder (JDK)  avgt   10  2919,350 ± 1101,942  us/op

图形(性能测试取决于 Windows 7 系统中的输入流长度)
enter image description here

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

 length  182    546     1092    3276    9828    29484   58968

 test8  0.38    0.938   1.868   4.448   13.412  36.459  72.708
 test4  2.362   3.609   5.573   12.769  40.74   81.415  159.864
 test5  3.881   5.075   6.904   14.123  50.258  129.937 166.162
 test9  2.237   3.493   5.422   11.977  45.98   89.336  177.39
 test6  1.261   2.12    4.38    10.698  31.821  86.106  186.636
 test7  1.601   2.391   3.646   8.367   38.196  110.221 211.016
 test1  1.529   2.381   3.527   8.411   40.551  105.16  212.573
 test3  3.035   3.934   8.606   20.858  61.571  118.744 235.428
 test2  3.136   6.238   10.508  33.48   43.532  118.044 239.481
 test10 1.593   4.736   7.527   20.557  59.856  162.907 323.147
 test11 3.913   11.506  23.26   68.644  207.591 600.444 1211.545

答案 2

一个很好的方法是使用Apache共享资源将...类似的东西IOUtilsInputStreamStringWriter

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