Java.io.PushbackReader.unread() 方法



描述

java.io.PushbackReader.unread(char[] cbuf) 方法將字元陣列推回,將其複製到回退緩衝區的前面。此方法返回後,下一個要讀取的字元的值將為 cbuf[0],下一個字元的值將為 cbuf[1],依此類推。

宣告

以下是 java.io.PushbackReader.unread() 方法的宣告。

public void unread(char[] cbuf)

引數

cbuf − 要回退的字元陣列。

返回值

此方法不返回值。

異常

IOException − 如果回退緩衝區空間不足,或發生其他 I/O 錯誤。

示例

以下示例演示了 java.io.PushbackReader.unread() 方法的用法。

package com.tutorialspoint;

import java.io.*;

public class PushbackReaderDemo {
   public static void main(String[] args) {
      String s = "Hello World";

      // create a new StringReader
      StringReader sr = new StringReader(s);

      // create a new PushBack reader based on our string reader
      PushbackReader pr = new PushbackReader(sr, 20);

      try {
         // read the first five chars
         for (int i = 0; i < 5; i++) {
            char c = (char) pr.read();
            System.out.print("" + c);
         }

         // change line
         System.out.println();

         // create a new array to unread
         char cbuf[] = {'w', 'o', 'r', 'l', 'd'};

         // unread into cbuf
         pr.unread(cbuf);

         // read five chars, which is what we unread from cbuf
         for (int i = 0; i < 5; i++) {
            char c = (char) pr.read();
            System.out.print("" + c);
         }

         // close the stream
         pr.close();

      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

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

Hello
world
java_io_pushbackreader.htm
廣告
© . All rights reserved.