Java.io.PipedInputStream.read() 方法



描述

java.io.PipedInputStream.read(byte[] b int off, int len) 方法從該管道輸入流中讀取最多 len 個位元組的資料到一個位元組陣列中。如果到達資料流的末尾或 len 超過管道的緩衝區大小,則讀取的位元組數將小於 len。如果 len 為零,則不讀取任何位元組並返回 0;否則,該方法會阻塞,直到至少有 1 個位元組的輸入可用、檢測到流的末尾或丟擲異常。

宣告

以下是 java.io.PipedInputStream.read() 方法的宣告。

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

引數

  • b − 讀取資料的目標緩衝區。

  • off − 目標陣列 b 中的起始偏移量。

  • len − 讀取的最大位元組數。

返回值

此方法返回寫入緩衝區的總位元組數,如果由於到達流的末尾而沒有更多資料,則返回 -1。

異常

  • NullPointerException − 如果 b 為 null。

  • IndexOutOfBoundsException − 如果 off 為負數,len 為負數,或 len 大於 b.length - off。

  • IOException − 如果管道已損壞、未連線、已關閉或發生 I/O 錯誤。

示例

以下示例演示了 java.io.PipedInputStream.read() 方法的使用。

package com.tutorialspoint;

import java.io.*;

public class PipedInputStreamDemo {
   public static void main(String[] args) {
   
      // create a new Piped input and Output Stream
      PipedOutputStream out = new PipedOutputStream();
      PipedInputStream in = new PipedInputStream();

      try {
         // connect input and output
         in.connect(out);

         // write something 
         out.write(70);
         out.write(71);

         // read what we wrote into an array of bytes
         byte[] b = new byte[2];
         in.read(b, 0, 2);

         // print the array as a string
         String s = new String(b);
         System.out.println("" + s);
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

讓我們編譯並執行上述程式,這將產生以下結果:

FG
java_io_pipedinputstream.htm
廣告