回滾流(回退流)——PushbackInputStream

回滾流——PushbackInputStream,可以將數據重新推入流中,然後再重新讀出。很多人說這個類是爲了將不需要的數據重新推入流中,我個人覺得,這樣解釋並不合理,不需要的數據之間丟掉不就好了嘛!幹嘛還要壓回去!

個人認爲,回滾流主要用於在讀取數據時,不確定自己需要讀取多少數據時來使用。比如我之前的博客,(H.264視頻碼流解析)在解析h264文件時確定NAL的位置,NAL 的位置不確定,長度也不確定(3或4個字節),當你取了前三字節發現不是,然後又取第四字節,再將這些數據重新處理成4長度的byte[] ,或者相反就很麻煩,而有了回滾流,我讀取三個發現不是,然後退回去,重新讀4個,就很方便!

PushbackInputStream類的常用方法

1、public PushbackInputStream(InputStream in) 構造方法 將輸入流放入到回退流之中。
2、public int read() throws IOException   普通  讀取數據。
3、public int read(byte[] b,int off,int len) throws IOException 普通方法 讀取指定範圍的數據。
4、public void unread(int b) throws IOException 普通方法 回退一個數據到緩衝區前面。
5、public void unread(byte[] b) throws IOException 普通方法 回退一組數據到緩衝區前面。
6、public void unread(byte[] b,int off,int len) throws IOException 普通方法 回退指定範圍的一組數據到緩衝區前面。

 示例:

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;

public class Tests {
	public static void main(String[] args) throws IOException {
		
		String str = "01asdf001asdfs001as01";//示例文本
		
		//內存流(字節數組流) 不懂可以參考博客https://danddx.blog.csdn.net/article/details/89429886
		ByteArrayInputStream source = new ByteArrayInputStream(str.getBytes());
		
		PushbackInputStream in = new PushbackInputStream(source,30);
		
		/**
		 * 演示目標 輸出流中的數字(2-3位)
		 */
		
		byte[] b3 = new byte[3];
		byte[] b2 = new byte[2];
		
		
		int len = 1;
		while(len>0) {
			len = in.read(b2);
			if("01".equals(new String(b2))) {
				b2 = new byte[2]; 
				System.out.println("01");
				continue;
			}
			in.unread(b2);
			len = in.read(b3);
			if("001".equals(new String(b3))) {
				b3 = new byte[3];//刷新緩衝區
				System.out.println("001");
				continue;
			}
			in.unread(b3);
			len = in.read();//丟棄一個字節的數據
		}
		
	}
}

輸出結果:

ps:與 PushbackInputStream功能類似的還有任意流(隨機流)——RandomAccessFile,與PushbackInputStream不同的是RandomAccessFile只能操作文件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章