Java Sting 将InputStream转换为字符串

来源:这里教程网 时间:2026-02-17 20:07:29 作者:

以下是如何读取InputStream并将其转换为String的完整示例。涉及的步骤是:

1)我使用getBytes()方法 将文件内容转换为字节之后,使用包含内部缓冲区的ByteArrayInputStream初始化InputStream,缓冲区包含可以从流中读取的字节。

2)使用InputStreamReader读取InputStream 。

3)使用BufferedReader读取InputStreamReader。

4)将BufferedReader读取的每一行附加到StringBuilder对象上。

5)最后使用toString()方法将StringBuilder转换为String。

import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;public class Example {   public static void main(String[] args) throws IOException {       InputStreamReader isr = null;       BufferedReader br = null;       InputStream is =             new ByteArrayInputStream("This is the content of my file".getBytes());       StringBuilder sb = new StringBuilder();       String content;       try {           isr = new InputStreamReader(is);       br = new BufferedReader(isr);       while ((content = br.readLine()) != null) {        sb.append(content);       }    } catch (IOException ioe) {        System.out.println("IO Exception occurred");        ioe.printStackTrace();         } finally {        isr.close();        br.close();          }        String mystring = sb.toString();    System.out.println(mystring);   }}

输出:

This is the content of my file

相关推荐