🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 在 Java 中将`InputStream`转换为字符串 > 原文: [https://howtodoinjava.com/java/io/how-to-read-data-from-inputstream-into-string-in-java/](https://howtodoinjava.com/java/io/how-to-read-data-from-inputstream-into-string-in-java/) 学习使用`BufferedReader`,`Scanner`和`IOUtils`类**将`InputStream`转换为字符串**。 从`InputStream`读取字符串在几种类型的应用程序中是非常普遍的要求,在这些应用程序中,您需要从网络流或文件系统中读取数据并对其进行一些操作。 如果使用`java.nio`包读取文件,则可以使用 [**Java NIO 中的 3 种读取文件的有效方法**](//howtodoinjava.com/java-7/nio/3-ways-to-read-files-using-java-nio/ "3 ways to read files using Java NIO")。 但是,如果您仍在使用旧的 Java IO 类,或者愿意使用**将文件读取为字符串**的任何新有效方式,那么您来对地方了。 ```java Table of Contents 1\. InputStream to String using Guava 2\. BufferedReader 3\. IOUtils 4\. java.util.Scanner ``` ![io-read-into-string](https://img.kancloud.cn/51/7d/517dcee22c77eb2ae4c2cc24f770253d_575x191.png) ## 1\. 使用 Google Guava IO 将`InputStream`转换为`String` Guava 库具有一些非常有用的类和方法来执行 IO 操作。 这些类隐藏了所有复杂性,否则就会暴露出来。 #### 1.1 Maven Google Guava 的 Maven 依赖关系。 ```java <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>26.0-jre</version> </dependency> ``` #### 1.2 字节源 Java 程序使用 Google Guava 库中的`ByteSource`类将`InputStream`读取为`String`。 ```java package com.howtodoinjava.demo; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import com.google.common.base.Charsets; import com.google.common.io.ByteSource; public class Main { public static void main(String[] args) throws Exception { InputStream inputStream = new FileInputStream(new File("C:/temp/test.txt")); ByteSource byteSource = new ByteSource() { @Override public InputStream openStream() throws IOException { return inputStream; } }; String text = byteSource.asCharSource(Charsets.UTF_8).read(); System.out.println(text); } } ``` #### 1.2 字符流 Java 程序,用于使用 Google Guava 库中的`CharStreams`类将`InputStream`转换为`String`。 ```java 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\. 使用`BufferedReader`将`InputStream`转换为`String` 使用[`BufferedReader`](https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html)是**将文件读入字符串**的最简单和流行的方法。 它有助于**逐行**读取输入流。 ```java 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`](https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/IOUtils.html)将文件内容读入`String`。 它使代码**更清晰**,并且易于阅读。 它也是**快速**的。 使用两种方法之一: 1. **`IOUtils.copy()`** 2. **`IOUtils.toString()`** ```java 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` 使用[扫描器](https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html)类不是​​很流行,但是可以使用。 它起作用的原因是因为`Scanner`对流中的标记进行迭代,并且在此过程中,我们可以使用“输入边界的起点”(A)来分隔标记,因此仅给我们一个流的整个内容的标记。 ```java 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(); } } ``` 就这样。 这篇文章的目的是为特定目的提供快速链接,即**将输入流读取到字符串**中。 [**下载源码**](https://docs.google.com/file/d/0B7yo2HclmjI4MjI3VlR5RkpTU0U/edit?usp=sharing) 学习愉快!