PushbackReader
是一个字符流读取器,允许将一个或多个字符推回到流中。
以下是PushbackReader
类的示例。文件:PushbackReaderExample.java –
package com.yiibai.tutorial.io; import java.io.IOException; import java.io.PushbackReader; import java.io.StringReader; /** * @author yiibai */ public class PushbackReaderExample { public static void main(String[] args) { String input = "This is an example of PushbackReader."; StringReader stringReader = null; PushbackReader pushbackReader = null; try { stringReader = new StringReader(input); pushbackReader = new PushbackReader(stringReader, 20); // Read first character int ch = pushbackReader.read(); System.out.println((char) ch); // Push back first character pushbackReader.unread(ch); char[] c = new char[4]; // Get first four characters pushbackReader.read(c); System.out.println(new String(c)); // Push back first four characters pushbackReader.unread(c, 0, 4); // Read all characters c = new char[input.length()]; pushbackReader.read(c); System.out.println(new String(c, 0, input.length())); } catch (IOException e) { e.printStackTrace(); } finally { try { if (pushbackReader != null) { pushbackReader.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
执行上面示例代码,得到以下结果:
T This This is an example of PushbackReader.
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264104.html