Java IO Tutorial - Java InputStream.read(byte[] b, int off, int len)








Syntax

InputStream.read(byte[] b, int off, int len) has the following syntax.

public int read(byte[] b, int off, int len)  throws IOException

Example

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

//from  www  .  ja va 2  s  . co m

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

public class Main {
  public static void main(String[] args) throws Exception {

    byte[] buffer = new byte[5];

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

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

    // read stream data into buffer
    is.read(buffer, 2, 3);

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

      // convert byte to character
      if (b == 0)// if b is empty
        c = '-';
      else        
        c = (char) b;// if b is read
      System.out.print(c);
    }
    is.close();
  }
}