Java InputStream read to String by InputStreamReader and BufferedReader

Description

Java InputStream read to String by InputStreamReader and BufferedReader

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Main {
  public static void main(String[] argv) {

    try {/*from  w ww  .jav a  2 s .  com*/
      InputStream is = new FileInputStream("Main.java");
      String s = fileInputStream2String(is);
      System.out.println(s);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
  public static final String fileInputStream2String(InputStream is) {
    BufferedReader br;
    StringBuilder strBlder = new StringBuilder();
    try {
      br = new BufferedReader(new InputStreamReader(is));
      String line = "";
      while (null != (line = br.readLine())) {
        strBlder.append(line + "\n");
      }
      br.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return strBlder.toString();
  }
}



PreviousNext

Related