Java.io.PushbackInputStream.read() 方法



描述

java.io.PushbackInputStream.read(byte[] b,int off,int len) 方法從該輸入流讀取最多 len 個位元組的資料到位元組陣列中。此方法首先讀取任何回退的位元組;之後,如果讀取的位元組少於 len 個,則從底層輸入流讀取。如果 len 不為零,則該方法會阻塞,直到至少有 1 個位元組的輸入可用;否則,不讀取任何位元組並返回 0。

宣告

以下是java.io.PushbackInputStream.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 − 如果透過呼叫其 close() 方法關閉了此輸入流,或者發生 I/O 錯誤。

示例

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

package com.tutorialspoint;

import java.io.*;

public class PushbackInputStreamDemo {
   public static void main(String[] args) {

      // declare a buffer and initialize its size:
      byte[] arrByte = new byte[1024];

      // create an array for our message
      byte[] byteArray = new byte[]{'H', 'e', 'l', 'l', 'o'};

      // create object of PushbackInputStream class for specified stream
      InputStream is = new ByteArrayInputStream(byteArray);
      PushbackInputStream pis = new PushbackInputStream(is);

      try {
         // read a char into our array
         pis.read(arrByte, 0, 3);

         // print arrByte
         for (int i = 0; i < 3; i++) {
            System.out.print((char) arrByte[i]);
         }
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

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

Hel
java_io_pushbackinputstream.htm
廣告
© . All rights reserved.