Java I/O 教程(六) BufferedInputStream 类
Java BufferedInputStream Class
Java BufferedInputStream class 用于从输入流读取数据,和BufferedOutStream一样内部使用缓冲机制提高读取性能。
需要注意的是:
当读取流中字节时,内部缓冲区每次会自动重新填满多个字节。
当一个缓冲输入流创建时,一个内部缓冲区数组也会创建。
类定义
public class BufferedInputStream extends FilterInputStream
构造函数
BufferedInputStream(InputStream in)
Creates a BufferedInputStream and saves its argument, the input stream in, for later use.
BufferedInputStream(InputStream in, int size)
Creates a BufferedInputStream with the specified buffer size, and saves its argument, the input stream in, for later use.
方法
int available() 返回输入流中预计可读取字节数
int read() 从输入流读取下一个字节
int read(byte[] b, int off, int ln) 从指定的byte输入流接收数据后写入指定字节数组中,从指定偏移量开始
void close() 关闭输入流并释放任何与流相关的系统资源
void reset() 复位在mark方法最后一次调用的位置
void mark(int readlimit) 其实就是给输入流在读取到某个字节时候打个标记,让reset方法能够回到这个标记的位置
long skip(long x) 跳过并抛弃x个字节
boolean markSupported() 用于测试输入流是否支持mark和reset方法
例子
package com.dylan.io;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
/**
* @author laoxu
* @create 2018-01-01
**/
public class BufferedInputStreamExample {
public static void main(String[] args) {
try {
FileInputStream fin = new FileInputStream("D:\\testout.txt");
BufferedInputStream bin = new BufferedInputStream(fin);
int i;
while ((i = bin.read()) != -1) {
//如果是中文,此方法不支持
System.out.print((char)i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出:Hello java.io!
关于mark和reset方法例子
package com.dylan.io;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
/**
* @author laoxu
* @create 2018-01-01
**/
public class BufferedInputStreamMarkReset {
public static void main(String[] args) throws Exception {
InputStream iStream = null;
BufferedInputStream bis = null;
try {
// read from file c:/test.txt to input stream
iStream = new FileInputStream("D:/testmark.txt");
// input stream converted to buffered input stream
bis = new BufferedInputStream(iStream);
// read and print characters one by one
System.out.println("Char : " + (char) bis.read());
System.out.println("Char : " + (char) bis.read());
System.out.println("Char : " + (char) bis.read());
// mark is set on the input stream
bis.mark(0);
System.out.println("Char : " + (char) bis.read());
System.out.println("reset() invoked");
// reset is called
bis.reset();
// read and print characters
System.out.println("char : " + (char) bis.read());
System.out.println("char : " + (char) bis.read());
} catch (Exception e) {
e.printStackTrace();
} finally {
// releases any system resources associated with the stream
if (iStream != null)
iStream.close();
if (bis != null)
bis.close();
}
}
}
输出:
Char : A
Char : B
Char : C
Char : D
reset() invoked
char : D
char : E
下一章