
将InputStream转换为String经常在Java开发使用,下面详解InputStream转String的详细步骤。
第一步:从InputStream中读取数据
如下示例:
// 创建一个InputStream对象,用于读取名为input.txt的文件
InputStream inputStream = new FileInputStream("input.txt");
第二步:将读取的数据转换为String对象
如下示例:
// 将InputStream中的数据读取到内存中
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
// 将读取的数据转换为String对象
String str = result.toString("UTF-8");
以下是完整的的InputStream转换为String示例代码:
import java.io.*;
public class InputStreamToStringDemo {
public static void main(String[] args) {
try {
// 创建一个InputStream对象,用于读取名为input.txt的文件
InputStream inputStream = new FileInputStream("input.txt");
// 将InputStream中的数据读取到内存中
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
// 将读取的数据转换为String对象
String str = result.toString("UTF-8");
// 关闭输入流
inputStream.close();
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的示例中,主要分为如下几个步骤:
- 我们首先创建一个InputStream对象inputStream,用于读取名为input.txt的文件。
- 然后创建一个ByteArrayOutputStream对象result,用于将InputStream中的数据读取到内存中。
- 在while循环中,每次从输入流中读取数据,将数据写入到ByteArrayOutputStream对象result中。
- 最后,我们通过调用ByteArrayOutputStream类的toString()方法将读取的数据转换为String对象,并关闭输入流。
关于mikechen
mikechen睿哥,10年+大厂架构经验,资深技术专家,就职于阿里巴巴、淘宝、百度等一线互联网大厂。
关注「mikechen」公众号,获取更多技术干货!