PushbackReader read() method in Java with Examples

2025年5月8日 | 阅读 4 分钟

在 Java 中,使用 PushbackReader 类的 read() 方法从流中读取单个字符。能够“取消读取”一个字符并在稍后重新处理它,使其可以用于顺序字符读取。此功能在需要前瞻或回溯的标记器或解析器中非常有用。除了 Reader 类的功能之外,PushbackReader 还通过启用一个小缓冲区来保存未读取的字符来扩展流读取。这种方法会阻止流,直到

  • 它已包含一些流输入。
  • 发生了一个 IOException。
  • 它已经读到流的末尾。

语法

参数:上述方法不接受任何参数。

返回值:上面方法返回的值是从流中读取的整数值。可能范围是 0 到 65535。如果没有读取字符,则返回 -1。

异常:如果输入或输出过程中发生错误,上面的函数将引发 IOException。

示例 1

此代码演示了使用 PushbackReader 从字符串中读取字符。通过围绕 StringReader 的 PushbackReader,StringReader 作为底层流。read() 方法打印从流中依次检索的前八个字符的整数ASCII 值和匹配的字符。尽管没有利用 PushbackReader 的“回推”功能,但该应用程序展示了其逐字符读取功能。close() 方法处理沿途的异常,确保 reader 流被有效关闭。

实施

文件名: PushbackReaderExample1.java

输出

The Integer value of the character read is: 72
The Actual character read is: H
The Integer value of the character read is: 101
The Actual character read is: e
The Integer value of the character read is: 108
The Actual character read is: l
The Integer value of the character read is: 108
The Actual character read is: l
The Integer value of the character read is: 111
The Actual character read is: o
The Integer value of the character read is: 32
The Actual character read is:  
The Integer value of the character read is: 87
The Actual character read is: W
The Integer value of the character read is: 111
The Actual character read is: o
The Stream is Closed.

示例 2

该代码使用围绕 StringReader 的 PushbackReader 逐个读取字符串 "Hello World" 中的字符。使用 read() 方法一次检索一个字符,该方法输出匹配的字符和字符的整数(ASCII)值。由于循环读取的字符数等于输入字符串的长度 11 个,因此 reader 可以处理整个流。代码中使用 close() 方法来确保 reader 被正确关闭。然而,这个例子并没有利用 PushbackReader 的“回推”功能。通过处理异常来确保程序的稳定性。

实施

文件名: PushbackReaderExample2.java

输出

 
The Integer value of the character read is: 72
The Actual character read is: H
The Integer value of the character read is: 101
The Actual character read is: e
The Integer value of the character read is: 108
The Actual character read is: l
The Integer value of the character read is: 108
The Actual character read is: l
The Integer value of the character read is: 111
The Actual character read is: o
The Integer value of the character read is: 32
The Actual character read is:  
The Integer value of the character read is: 87
The Actual character read is: W
The Integer value of the character read is: 111
The Actual character read is: o
The Integer value of the character read is: 114
The Actual character read is: r
The Integer value of the character read is: 108
The Actual character read is: l
The Integer value of the character read is: 100
The Actual character read is: d
The Stream is Closed.