Java IO Tutorial - Java InputStream.read(byte[] b)








Syntax

InputStream.read(byte[] b) has the following syntax.

public int read(byte[] b)  throws IOException

Example

In the following code shows how to use InputStream.read(byte[] b) method.

import java.io.FileInputStream;
import java.io.InputStream;
//w w  w  . ja  v a2s  . co m
public class Main {
  public static void main(String[] args) throws Exception {

    byte[] buffer = new byte[5];

    // new input stream created
    InputStream is = new FileInputStream("C://test.txt");

    System.out.println("Characters printed:");

    // read stream data into buffer
    is.read(buffer);

    // for each byte in the buffer
    for (byte b : buffer) {
      // convert byte to character
      char c = (char) b;

      // prints character
      System.out.print(c);
    }
    is.close();
  }
}