原文: https://howtodoinjava.com/java/io/how-to-read-data-from-inputstream-into-string-in-java/

学习使用BufferedReaderScannerIOUtilsInputStream转换为字符串。 从InputStream读取字符串在几种类型的应用程序中是非常普遍的要求,在这些应用程序中,您需要从网络流或文件系统中读取数据并对其进行一些操作。

如果使用java.nio包读取文件,则可以使用 Java NIO 中的 3 种读取文件的有效方法。 但是,如果您仍在使用旧的 Java IO 类,或者愿意使用将文件读取为字符串的任何新有效方式,那么您来对地方了。

  1. Table of Contents
  2. 1\. InputStream to String using Guava
  3. 2\. BufferedReader
  4. 3\. IOUtils
  5. 4\. java.util.Scanner

在 Java 中将`InputStream`转换为字符串 - 图1

1. 使用 Google Guava IO 将InputStream转换为String

Guava 库具有一些非常有用的类和方法来执行 IO 操作。 这些类隐藏了所有复杂性,否则就会暴露出来。

1.1 Maven

Google Guava 的 Maven 依赖关系。

  1. <dependency>
  2. <groupId>com.google.guava</groupId>
  3. <artifactId>guava</artifactId>
  4. <version>26.0-jre</version>
  5. </dependency>

1.2 字节源

Java 程序使用 Google Guava 库中的ByteSource类将InputStream读取为String

  1. package com.howtodoinjava.demo;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import com.google.common.base.Charsets;
  7. import com.google.common.io.ByteSource;
  8. public class Main
  9. {
  10. public static void main(String[] args) throws Exception
  11. {
  12. InputStream inputStream = new FileInputStream(new File("C:/temp/test.txt"));
  13. ByteSource byteSource = new ByteSource() {
  14. @Override
  15. public InputStream openStream() throws IOException {
  16. return inputStream;
  17. }
  18. };
  19. String text = byteSource.asCharSource(Charsets.UTF_8).read();
  20. System.out.println(text);
  21. }
  22. }

1.2 字符流

Java 程序,用于使用 Google Guava 库中的CharStreams类将InputStream转换为String

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import com.google.common.io.CharStreams;

public class Main 
{
    public static void main(String[] args) throws Exception
    {
        InputStream inputStream = new FileInputStream(new File("C:/temp/test.txt"));

        String text = null;

        try (final Reader reader = new InputStreamReader(inputStream)) {
            text = CharStreams.toString(reader);
        }

        System.out.println(text);
    }
}

2. 使用BufferedReaderInputStream转换为String

使用BufferedReader将文件读入字符串的最简单和流行的方法。 它有助于逐行读取输入流。

package com.howtodoinjava.demo.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ReadStreamIntoStringUsingReader
{
    public static void main(String[] args) throws FileNotFoundException, IOException 
    {
        InputStream in = new FileInputStream(new File("C:/temp/test.txt"));
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder out = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            out.append(line);
        }
        System.out.println(out.toString());   //Prints the string content read from input stream
        reader.close();
    }
}

3. Apache Commons IOUtils(最易读)

Apache commons 有一个非常有用的类IOUtils将文件内容读入String。 它使代码更清晰,并且易于阅读。 它也是快速的。

使用两种方法之一:

  1. IOUtils.copy()
  2. IOUtils.toString()
package com.howtodoinjava.demo.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;

import org.apache.commons.io.IOUtils;

public class ReadStreamIntoStringUsingIOUtils
{
    public static void main(String[] args) throws FileNotFoundException, IOException 
    {
        //Method 1 IOUtils.copy()

        StringWriter writer = new StringWriter();
        IOUtils.copy(new FileInputStream(new File("C:/temp/test.txt")), writer, "UTF-8");
        String theString = writer.toString();
        System.out.println(theString);

        //Method 2 IOUtils.toString()

        String theString2 = IOUtils.toString(new FileInputStream(new File("C:/temp/test.txt")), "UTF-8");
        System.out.println(theString2);
    }
}

4. 使用扫描器将 Java InputStream转换为String

使用扫描器类不是很流行,但是可以使用。 它起作用的原因是因为Scanner对流中的标记进行迭代,并且在此过程中,我们可以使用“输入边界的起点”(A)来分隔标记,因此仅给我们一个流的整个内容的标记。

package com.howtodoinjava.demo.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadStreamIntoStringUsingScanner
{
    @SuppressWarnings("resource")
    public static void main(String[] args) throws FileNotFoundException, IOException 
    {
        FileInputStream fin = new FileInputStream(new File("C:/temp/test.txt"));
        java.util.Scanner scanner = new java.util.Scanner(fin,"UTF-8").useDelimiter("\A");
        String theString = scanner.hasNext() ? scanner.next() : "";
        System.out.println(theString);
        scanner.close();
    }
}

就这样。 这篇文章的目的是为特定目的提供快速链接,即将输入流读取到字符串中。

下载源码

学习愉快!