Java.io.PushbackInputStream.read() 方法



描述

java.io.PushbackInputStream.read() 方法讀取此輸入流中的下一個位元組資料。該位元組值作為 int 型別返回,範圍為 0 到 255。如果由於已到達流的末尾而沒有可用的位元組,則返回 -1。此方法會阻塞,直到輸入資料可用、檢測到流的末尾或丟擲異常。

此方法返回最近回退的位元組(如果存在),否則呼叫其底層輸入流的 read 方法並返回該方法返回的任何值。

宣告

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

public int read()

引數

返回值

此方法返回下一個位元組的資料,如果已到達流的末尾,則返回 -1。

異常

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 from the buffer one character at a time
         for (int i = 0; i < byteArray.length; i++) {

            // read a char into our array
            arrByte[i] = (byte) pis.read();

            // display the read byte
            System.out.print((char) arrByte[i]);
         }
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

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

Hello
java_io_pushbackinputstream.htm
廣告

© . All rights reserved.