Java InputStream read to String by converting byte array to String

Description

Java InputStream read to String by converting byte array to String

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

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

    try {//www. j  av  a2  s  .  c  o  m
      InputStream is = new FileInputStream("Main.java");
      String s = stringFromStream(is);
      System.out.println(s);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static String stringFromStream(InputStream is) throws IOException {
    StringBuffer sb = new StringBuffer();
    byte[] b = new byte[4096];
    int n;
    while ((n = is.read(b)) != -1) {
      sb.append(new String(b, 0, n));
    }
    return sb.toString();
  }
}



PreviousNext

Related