Java.io.PushbackReader.unread() 方法



描述

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

宣告

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

public void unread(char[] cbuf,int off,int len)

引數

  • cbuf − 要推回的字元陣列。

  • off − 要推回的第一個字元的偏移量。

  • len − 要推回的字元數。

返回值

此方法不返回值。

異常

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, 1, 4);

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

         // close the stream
         pr.close();

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

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

Hello
orld
java_io_pushbackreader.htm
廣告

© . All rights reserved.