Java FilterInputStream.read(byte[] b, int off, int len)方法範例

2019-10-16 22:13:56

Java FilterInputStream.read(byte[] b, int off, int len)方法範例

FilterInputStream.read(byte[] b, int off, int len)方法具有以下語法。

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

範例

在下面的程式碼中展示了如何使用FilterInputStream.read(byte[] b, int off, int len)方法。

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.InputStream;
// By: WW  W.Y I i Ba i .c  o m 
public class Main {
  public static void main(String[] args) throws Exception {

    byte[] buffer = new byte[6];

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

    // returns number of bytes read to buffer
    int i = fis.read(buffer, 2, 4);

    System.out.println("Number of bytes read: " + i);

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

      // if byte is null
      if (b == 0){
        c = '-';
      }
      System.out.println("Char read from buffer b: " + c);
    }

  }
}