Java I/O How to - Read from file from Buffered InputStream








Question

We would like to know how to read from file from Buffered InputStream.

Answer

/*from w  w w  .  j av a 2  s  .  co  m*/
import java.io.BufferedInputStream;
import java.io.FileInputStream;

public class Main {
  public static void main(String[] args) throws Exception {
    byte[] buffer = new byte[1024];
    BufferedInputStream bufferedInput = new BufferedInputStream(new FileInputStream("filename.txt"));

    int bytesRead = 0;
    while ((bytesRead = bufferedInput.read(buffer)) != -1) {
      String chunk = new String(buffer, 0, bytesRead);
      System.out.print(chunk);
    }
    bufferedInput.close();
  }
}