流的效率:
BufferedInputStream&&BufferedOutputStream:
流效率图解:
自定义带缓冲区的字节输入流(BufferedInputStream):
class MyBufferedInputStream{
//默认的缓冲区大小
public static final int DEFAULT_BUF_SIZE = 8192;
//字节数组缓冲区
private byte[] buf = new byte[DEFAULT_BUF_SIZE];
//用于访问底层数据的流
private InputStream is;
//用于记录读取到当前 buf 中字节数据的位置
private int pos;
//记录缓冲区中 待读取的字节数
private int count;
public MyBufferedInputStream(InputStream is) {
super();
this.is = is;
}
/**
* 从缓冲区中读取下一个字节的数据,如果数据到大了末尾,返回 -1
* @return 读取到的字节数据的 int 形式,如果读取到了流的末尾 返回 -1
*/
public int read()throws Exception{
//缓冲区没有数据
if(count == 0){
//通过底层的输入流,一次性读取 8192 个字节数据到缓冲区中来。
count = is.read(buf);
//is 没有读取到数据
if(count == -1){
return -1;
}
//is 读取到数据了 返回第一个字节数据
pos = 0;
byte value = buf[pos++];
count --;
return value & 0xff;
}else{//缓冲区有数据
count --;
return buf[pos++] & 0xff;
}
}
/**
* 处理流的关闭问题:只关闭处理流即可,处理流的关闭会将底层的流关闭掉。
* @throws IOException
*/
public void close() throws IOException{
if(is != null){
is.close();
}
}
}
自定义带缓冲区的字节输出流(BufferedOutputStream):
class MyBufferedOutputStream{
//默认的缓冲区大小
public static final int DEFAULT_BUF_SIZE = 8192;
//字节数组缓冲区
private byte[] buf = new byte[DEFAULT_BUF_SIZE];
//用于记录写入到缓冲区数组中的位置,还记录了写入的字节的个数
private int pos;
//底层的输出流
private OutputStream os;
public MyBufferedOutputStream(OutputStream os) {
super();
this.os = os;
}
//将b写出去
public void write(int b) throws Exception{
//buf 满了
if(pos == DEFAULT_BUF_SIZE){
//通过 os 将数据写出去
os.write(buf);
//将b 写入到缓冲区
pos = 0;
}
buf[pos] = (byte)b;
pos ++;
}
//将缓冲区的内容刷新到目的地
public void flush() throws IOException{
if(pos > 0){
os.write(buf, 0, pos);
pos = 0;
}
}
public void close() throws IOException{
if(os != null){
flush();
os.close();
}
}
}
public class MyBufferedStreamTest {
public static void main(String[] args) {
long time = System.currentTimeMillis();
bufferedCopy();
System.out.println("cost = "+(System.currentTimeMillis()-time));
}
static void bufferedCopy(){//7ms
MyBufferedInputStream mbis = null;
MyBufferedOutputStream mbos = null;
try {
mbis = new MyBufferedInputStream(new FileInputStream("c:/77.jpg"));
mbos = new MyBufferedOutputStream(new FileOutputStream("c:/77_copy_copy.jpg"));
int value = mbis.read();
while(value != -1){
//将读取到的内容写出去
mbos.write(value);
value = mbis.read();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(mbis != null){
try {
mbis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(mbos != null){
try {
mbos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}