目录

int read()

描述 (Description)

java.io.PushbackInputStream.read()方法从此输入流中读取下一个数据字节。 值字节作为int返回,范围为0到255.如果没有字节可用,因为已到达流的末尾,则返回值-1。 此方法将阻塞,直到输入数据可用,检测到流的末尾或抛出异常。

此方法返回最近推回的字节(如果有),否则调用其基础输入流的read方法并返回该方法返回的任何值。

声明 (Declaration)

以下是java.io.PushbackInputStream.read()方法的声明。

public int read()

参数 (Parameters)

NA

返回值 (Return Value)

此方法返回下一个数据字节,如果已到达流的末尾,则返回-1。

异常 (Exception)

IOException - 如果通过调用close()方法关闭此输入流,或发生I/O错误。

例子 (Example)

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

package com.iowiki;
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
↑回到顶部↑
WIKI教程 @2018