Skip to content

Latest commit

 

History

History
209 lines (150 loc) · 6.39 KB

187.md

File metadata and controls

209 lines (150 loc) · 6.39 KB

在 Java 中将InputStream转换为字符串

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

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

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

Table of Contents

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

io-read-into-string

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

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

1.1 Maven

Google Guava 的 Maven 依赖关系。

<dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>26.0-jre</version>
</dependency>

1.2 字节源

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

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

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();
	}
}

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

下载源码

学习愉快!