Java Sting 将InputStream转换为字符串

以下是如何读取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
赞(0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址