Java中如何将输入流转换为字符串呢?

书欣 Java经验 发布时间:2022-10-06 15:30:11 阅读数:2045 1
下文笔者讲述java代码中将输入流转换为字符串的方法分享,如下所示
实现思路:
    借助外部的工具类
	或借助Scanner类
	或InputStreamReader获取输入流中的数据
	并将其转换为字符串

借助commons-io类对输入流进行转换

例:
1.引入commons-io类
   Maven配置
<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.11.0</version>
</dependency>


2.编写以下代码IOUtils.toString(Apache Utils)
String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);

使用google guava中的相关方法进行转换

例:guava将输入流转换为字符
1.Maven 配置
<dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>18.0</version>
</dependency>


2.使用CharStreams(Guava)
String result = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));

借助JDK中的Scanner将流转换为字符串

 使用 Scanner (JDK)
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
String result = s.hasNext() ? s.next() : "";

使用stream API将输入流转换为字符串

使用 Stream API (Java 8)
String result = new BufferedReader(new InputStreamReader(inputStream))
  .lines().collect(Collectors.joining("\n"));

使用 parallel Stream API (Java 8)
String result = new BufferedReader(new InputStreamReader(inputStream))
      .lines().parallel().collect(Collectors.joining("\n"));

使用 InputStreamReader and StringBuilder (JDK)

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 and IOUtils.copy (Apache Commons)

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, "UTF-8");
return writer.toString();

使用 ByteArrayOutputStream and inputStream.read (JDK)

ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int length; (length = inputStream.read(buffer)) != -1; ) {
    result.write(buffer, 0, length);
}

return result.toString("UTF-8");

使用 BufferedReader (JDK)

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 and ByteArrayOutputStream (JDK)

BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
for (int result = bis.read(); result != -1; result = bis.read()) {
   buf.write((byte) result);
}

return buf.toString("UTF-8");

使用 inputStream.read() and StringBuilder (JDK)

StringBuilder sb = new StringBuilder();
for (int ch; (ch = inputStream.read()) != -1; ) {
    sb.append((char) ch);
}
return sb.toString();
注意事项:
    处理字符串转换时,注意Unicode的编码
例:
输入流转换为字符串方法大全
package com.java265;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.stream.Collectors;

import org.apache.commons.io.IOUtils;

import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
 
public class InputStreamToChar {

	public static void main(String[] args) throws IOException {
		InputStream inputStream = new FileInputStream(new File("java265testInfo.txt"));
		one(inputStream);
		two(inputStream);
		three(inputStream);
		four(inputStream);
		five(inputStream);
		six(inputStream);
		seven(inputStream);
		eight(inputStream);
		nine(inputStream);
		ten(inputStream);
		eleven(inputStream);
	}

	public static void one(InputStream inputStream) throws IOException {
		String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
		System.out.println(result);
	}

	public static void two(InputStream inputStream) throws IOException {
		String result = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
		System.out.println(result);
	}

	public static void three(InputStream inputStream) throws IOException {
		Scanner s = new Scanner(inputStream).useDelimiter("\\A");
		String result = s.hasNext() ? s.next() : "";
		System.out.println(result);
	}

	public static void four(InputStream inputStream) throws IOException {
		String result = new BufferedReader(new InputStreamReader(inputStream)).lines()
				.collect(Collectors.joining("\n"));
		System.out.println(result);
	}

	public static void five(InputStream inputStream) throws IOException {
		String result = new BufferedReader(new InputStreamReader(inputStream)).lines().parallel()
				.collect(Collectors.joining("\n"));
		System.out.println(result);
	}

	public static void six(InputStream inputStream) throws IOException {
		int bufferSize = 1024;
		char[] buffer = new char[bufferSize];
		StringBuilder out = new StringBuilder();
		Reader in = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
		for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0;) {
			out.append(buffer, 0, numRead);
		}
		String result = out.toString();
		System.out.println(result);
	}

	public static void seven(InputStream inputStream) throws IOException {
		StringWriter writer = new StringWriter();
		IOUtils.copy(inputStream, writer, "UTF-8");
		String result = writer.toString();
		System.out.println(result);
	}

	public static void eight(InputStream inputStream) throws IOException {
		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
		System.out.println(result.toString("UTF-8"));
	}

	public static void nine(InputStream inputStream) throws IOException {
		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);
		}
		System.out.println(result.toString());
	}

	public static void ten(InputStream inputStream) throws IOException {
		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
		System.out.println(buf.toString("UTF-8"));
	}

	public static void eleven(InputStream inputStream) throws IOException {
		StringBuilder sb = new StringBuilder();
		for (int ch; (ch = inputStream.read()) != -1;) {
			sb.append((char) ch);
		}
		System.out.println(sb.toString());
	}
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202210/16650414664575.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者