在Java中将输入流读取转换为字符串的11种方法

我找到了11种主要的方法来做到这一点(见下文)。

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

我们对Markdown编辑器进行了一些功能拓展与语法支持,除了标准的Markdown编辑器功能,我们增加了如下几点新功能,帮助你用它写博客:

  1. 使用 IOUtils.toString (Apache Utils)
String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);

Maven配置
<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.11.0</version>
</dependency>
  1. 使用 CharStreams (Guava)
 String result = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
 
Maven 配置
<dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>18.0</version>
</dependency>

  1. 使用 Scanner (JDK)
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
String result = s.hasNext() ? s.next() : "";
  1. 使用 Stream API (Java 8). 警告: 此解决方案将不同的换行符(如\r\n)转换为\n。
String result = new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining("\n"));
  1. 使用 parallel Stream API (Java 8). 警告: 这个解决方案将不同的换行符(如\r\n)转换为\n。
String result = new BufferedReader(new InputStreamReader(inputStream)).lines().parallel().collect(Collectors.joining("\n"));
  1. 使用 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();

  1. 使用 StringWriter and IOUtils.copy (Apache Commons)
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, "UTF-8");
return writer.toString();
  1. 使用 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);
}
// StandardCharsets.UTF_8.name() > JDK 7
return result.toString("UTF-8");
  1. 使用 BufferedReader (JDK). 警告: 这个解决方案将不同的换行符(如\n\r)转换为
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();

  1. 使用 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);
}
// StandardCharsets.UTF_8.name() > JDK 7
return buf.toString("UTF-8");

  1. 使用 inputStream.read() and StringBuilder (JDK). 注意: 这个解决方案在Unicode方面有问题,只能在非Unicode文本上正确工作
StringBuilder sb = new StringBuilder();
for (int ch; (ch = inputStream.read()) != -1; ) {
    sb.append((char) ch);
}
return sb.toString();

注意:

1、解决方案4、5、9此解决方案将不同的换行符(如\r\n转换为\n),(\r\n是Windows系统的换行符,而在Unix、Liunx等系统中的换行符为 \n)。
2、解决方案11不能正确地处理Unicode文本。

最后是所有源码全部总结测试(代码已经经过编写运行时间:2022年9月24日11:20:13):

package eleven.莱迪娜的风声;

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;

/**
 * 时间:2022年9月24日11:18:17
 * 
 * @author 莱迪娜的风声
 */
public class InputStreamToChar {

	public static void main(String[] args) throws IOException {
		InputStream inputStream = new FileInputStream(new File("Test.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());
	}
}

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个示例代,实现了您的需求: ```java import java.io.*; public class FileIOExample { public static void main(String[] args) { try { // 创建输入,从键盘读取数据 BufferedReader keyboardReader = new BufferedReader(new InputStreamReader(System.in)); // 创建输出,写入数据到文件中 FileWriter fileWriter = new FileWriter("test/myfile.txt"); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); System.out.println("请开始输入一串字符(以#号结束):"); String input; while ((input = keyboardReader.readLine()) != null && !input.equals("#")) { bufferedWriter.write(input); bufferedWriter.newLine(); // 每行数据后换行 } // 关闭输入输出 bufferedWriter.close(); fileWriter.close(); keyboardReader.close(); // 创建输入,从文件读取数据 FileReader fileReader = new FileReader("test/myfile.txt"); BufferedReader fileBufferedReader = new BufferedReader(fileReader); // 输出读取到的数据 String line; System.out.println("从文件读取到的字符串为:"); while ((line = fileBufferedReader.readLine()) != null) { System.out.println(line); } // 关闭输入 fileBufferedReader.close(); fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 代分为两部分,一部分用于从键盘输入数据并写入到文件中,另一部分从文件读取数据并输出到屏幕上。注释中有详细的解释。请注意,如果 `test` 文件夹不存在,则需要先创建该文件夹。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

莱迪娜的风声

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值