PushbackInputStream
将功能添加到另一个输入流以推回或读取一个字节。 PushbackInputStream
类的read()
方法从输入流中读取一个字节,而unread()
方法将一个字节推回输入流。
下面是一个演示如何使用PushbackInputStream
类的例子。
文件:PushbackInputStreamExample.java –
package com.yiibai.tutorial.io; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.PushbackInputStream; /** * @author yiibai */ public class PushbackInputStreamExample { public static void main(String[] args) { String data = "This an example of PushbackInputStream"; ByteArrayInputStream byteArrayInputStream = null; PushbackInputStream pushbackInputStream = null; try { byteArrayInputStream = new ByteArrayInputStream(data.getBytes()); pushbackInputStream = new PushbackInputStream(byteArrayInputStream); //Read first character from stream int i=pushbackInputStream.read(); System.out.println((char)i); //Push back first character to stream pushbackInputStream.unread(i); //Now Read full bytes byte b[] = new byte[data.getBytes().length]; pushbackInputStream.read(b); System.out.println(new String(b)); } catch (IOException e) { e.printStackTrace(); } finally { try { if (pushbackInputStream != null) { pushbackInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
执行上面示代码,得到以下结果:
T This an example of PushbackInputStream
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264109.html