當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java 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 為空。

  • 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.read() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。