Java IO 操作流之回退流-输入流的增强版
回退流失输入流的一种,具体用法如下:
public class PushbackInputStream extends FilterInputStream;// 字节输入回退流;
public PushbackInputStream(InputStream in,
int size)
Creates a PushbackInputStream with a pushback buffer of the specified size, and saves its argument, the input stream in, for later use. Initially, there is no pushed-back byte (the field pushBack is initialized to -1).
public PushbackInputStream(InputStream in);// 可以接收所有字节输入流
Creates a PushbackInputStream and saves its argument, the input stream in, for later use. Initially, there is no pushed-back byte (the field pushBack is initialized to -1).
public int read()
throws IOException
Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255.
public void unread(int b)
throws IOException;// 回退一字节的数据,
Pushes back a byte by copying it to the front of the pushback buffer. After this method returns, the next byte to be read will have the value (byte)b.
public void unread(byte[] b, int off,int len) throws IOException ;
public void close()
throws IOException;
2. public class PushbackReader extends FilterReader;// 字符输入回退流,对所有字符输入流的增强!
A character-stream reader that allows characters to be pushed back into the stream.
———回退内存输入流的实例:
package com.mldn;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.PushbackInputStream;
import java.io.IOException;
public class PushbackDemo
{
public static void main(String[] args) throws IOException
{
byte[] bytes = null; // 声明字节内存
bytes = new String(“Hello, World!”).getBytes(); // 实例化内存数组
InputStream input = null;// 声明字节输入流
PushbackInputStream pis = null; // 声明字节输入回退流
input = new ByteArrayInputStream(bytes); // 实例化内存输入流
pis = new PushbackInputStream(input); // 实例化字节输入回退流
int temp = 0;
StringBuffer pushback = new StringBuffer();
StringBuffer str = new StringBuffer();
while ((temp = pis.read()) != -1)
{
if (temp == ‘,’) // 若读的是’,’,回退到输入流缓冲区
{
pis.unread(temp);// 回退一个字节
pushback.append((char)pis.read()); // 将回退的字节读出到匿名变量
}
else
{
str.append((char)temp);
}
}
System.out.println(“回退数据:'” + pushback.toString() + “‘! ” + pushback.length() + “次!”);
System.out.println(“读取的内容为:”);
System.out.println(str);
}
}
/*
administrator@xu-desktop:~$ java com.mldn.PushbackDemo
回退数据:’,’! 1次!
读取的内容为:
Hello World!
*/
声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 嗅谱网
转载请注明:转自《Java IO 操作流之回退流-输入流的增强版》
本文地址:http://www.xiupu.net/archives-103.html
关注公众号:
微信赞赏
支付宝赞赏