Java PushbackInputStream给输入流增加了一个新的功能,即可以使用unread()方法将读取的字节数据推回读取的字节数据,例如小编test.txt文件内容为:www.tpyyes.com
Java PushbackInputStream用法:
import java.io.FileInputStream; import java.io.PushbackInputStream; public class Demo { public static void main(String[] args) { String path = "D:\\intelljIdeaSpace\\PlusbotChatSocket\\src\\test.txt"; try (PushbackInputStream pis = new PushbackInputStream(new FileInputStream(path))) { byte byteData; while ((byteData = (byte) pis.read()) != -1) { System.out.print((char) byteData); pis.unread(byteData); // Reread the byte we unread byteData = (byte) pis.read(); System.out.print((char) byteData); } } catch (Exception e2) { e2.printStackTrace(); } } }
因为读取过的数据被unread()方法推回到了输入流中,因此输出结果为: