learning java 推回输入流
import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PushbackReader; public class PushbackTest { public static void main(String[] args) { try { var pr = new PushbackReader(new FileReader("src/com/company/PushbackTest.java"),64); { var buf = new char[32]; var lastContent = ""; var hasRead = 0; while ((hasRead = pr.read(buf)) > 0){ var content = new String(buf,0 ,hasRead); var targetIndex = 0; if ((targetIndex = (lastContent + content).indexOf("new PushbackReader")) > 0){ pr.unread((lastContent+content).toCharArray()); if (targetIndex > 32){ buf = new char[targetIndex]; } pr.read(buf, 0 , targetIndex); System.out.println(new String(buf,0, targetIndex)); System.exit(0); } else { System.out.println(lastContent); lastContent = content; } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
output:
package com.company; import j ava.io.FileNotFoundException; i mport java.io.FileReader; impor t java.io.IOException; import j ava.io.PushbackReader; public class PushbackTest { publi c static void main(String[] args ) { try { var pr =