要在Java中将InputStream转换为String,可以使用以下方法: 使用Scanner类: 代码语言:java 复制 importjava.io.InputStream;importjava.util.Scanner;publicclassInputStreamToString{publicstaticvoidmain(String[]args){InputStreaminputStream=System.in;// 这里可以替换为您的InputStream实例Scannerscanner=newScanner(...
importjava.io.BufferedReader;// 导入 BufferedReader 类importjava.io.FileInputStream;// 导入 FileInputStream 类importjava.io.InputStream;// 导入 InputStream 类importjava.io.InputStreamReader;// 导入 InputStreamReader 类publicclassInputStreamToString{publicstaticvoidmain(String[]args){try{InputStreamin...
在Java中,将InputStream转换为String是一个常见的操作。以下是实现这一转换的步骤,以及相应的代码示例: 创建一个InputStream对象: 首先,需要有一个InputStream对象。这个对象可以从文件、网络连接等数据源获取。例如,从文件中获取InputStream: java File file = new File("example.txt"); InputStream inputStream =...
public void convertingAnInputStreamToAString() throws IOException { String originalString = randomString(8); InputStream inputStream = new ByteArrayInputStream(originalString.getBytes()); String text = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); assertThat(text, equalTo(originalStri...
stringBuilder.append(new String(buffer,0, readBytes)); } System.out.println(stringBuilder.toString()); } } 缓冲区的大小自己根据实际来调,比 BufferedReader 还简洁些,不需管换行符的事情。 本文原始链接:http://unmi.cc/java-convert-inputstream-to-string, 来自:隔叶黄莺 Unmi Blog ...
1、InputStream转化为String 1.1 JDK原生提供 方法一: byte[] bytes = new byte[0]; bytes = new byte[inputStream.available()]; inputStream.read(bytes); String str = new String(bytes); 方法二: String result = new BufferedReader(new InputStreamReader(inputStream)) ...
一个很好的方法是使用Apache commonsIOUtils将InputStream复制到StringWriter… StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, encoding); String theString = writer.toString(); 甚至 // NB: does not close inputStream, you'll have to use try-with-resources for that ...
Java 8 bringsa newlines()method to theBufferedReader. Let’s see how we can make use of it to convert anInputStreamto aString: @TestpublicvoidgivenUsingJava8_whenConvertingAnInputStreamToAString_thenCorrect(){StringoriginalString=randomAlphabetic(DEFAULT_SIZE);InputStreaminputStream=newByteArrayInput...
然后,您可以使用IOUtils类将InputStream转换为String: 代码语言:java 复制 import org.apache.commons.io.IOUtils; import java.io.InputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class InputStreamToString { public static void main(String[] args) { InputStrea...
步骤2: 使用BufferedReader读取InputStream 接下来,使用BufferedReader来读取InputStream中的内容: privatestaticStringconvertInputStreamToString(InputStreaminputStream)throwsException{BufferedReaderreader=newBufferedReader(newInputStreamReader(inputStream)); 1. ...