深入理解BufferedInputStream实现原理

来源:互联网 发布:网络合作合同 编辑:程序博客网 时间:2024/04/27 22:03

通过分析FileInputStream类和BufferedInputStream类中的部分核心代码来理解带缓冲的字节输入流的实现原理,缓冲输出流原理与之相同,在此不再赘述。

FileInputStream源码

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package java.io;  
  2.   
  3. public class FileInputStream extends InputStream{  
  4.       
  5.     /** 
  6.      *从输入流中读取一个字节 
  7.      *该方法为private私有方法,用户不能直接调用。 
  8.      *该方法为native本地方法,这是因为Java语言不能直接与操作系统或计算机硬件交互, 
  9.      *只能通过调用C/C++编写的本地方法来实现对磁盘数据的访问。 
  10.      */  
  11.     private native int read0() throws IOException;  
  12.     //调用native方法read0()每次读取一个字节  
  13.     public int read() throws IOException {  
  14.         Object traceContext = IoTrace.fileReadBegin(path);  
  15.         int b = 0;  
  16.         try {  
  17.             b = read0();  
  18.         } finally {  
  19.             IoTrace.fileReadEnd(traceContext, b == -1 ? 0 : 1);  
  20.         }  
  21.         return b;  
  22.     }  
  23.     /** 
  24.      * 从输入流中读取多个字节到byte数组中 
  25.      * 该方法也是私有本地方法,不对用户开放,只供内部调用。 
  26.      */  
  27.     private native int readBytes(byte b[], int off, int len) throws IOException;  
  28.   
  29.     //调用native方法readBytes(b, 0, b.length)每次读取多个字节  
  30.     public int read(byte b[]) throws IOException {  
  31.         Object traceContext = IoTrace.fileReadBegin(path);  
  32.         int bytesRead = 0;  
  33.         try {  
  34.             bytesRead = readBytes(b, 0, b.length);  
  35.         } finally {  
  36.             IoTrace.fileReadEnd(traceContext, bytesRead == -1 ? 0 : bytesRead);  
  37.         }  
  38.         return bytesRead;  
  39.     }  
  40.     //从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。  
  41.     public int read(byte b[], int off, int len) throws IOException {  
  42.         Object traceContext = IoTrace.fileReadBegin(path);  
  43.         int bytesRead = 0;  
  44.         try {  
  45.             bytesRead = readBytes(b, off, len);  
  46.         } finally {  
  47.             IoTrace.fileReadEnd(traceContext, bytesRead == -1 ? 0 : bytesRead);  
  48.         }  
  49.         return bytesRead;  
  50.     }  
  51.   
  52.       
  53. }  
通过源码可以看到,如果用read()方法读取一个文件,每读取一个字节就要访问一次硬盘,这种读取的方式效率是很低的。即便使用read(byte b[])方法一次读取多个字节,当读取的文件较大时,也会频繁的对磁盘操作。

为了提高字节输入流的工作效率,Java提供了BufferedInputStream类。

首先解释一下BufferedInputStream的基本原理:

API文档的解释:创建 BufferedInputStream时,会创建一个内部缓冲区数组。在读取流中的字节时,可根据需要从包含的输入流再次填充该内部缓冲区,一次填充多个字节。

也就是说,Buffered类初始化时会创建一个较大的byte数组,一次性从底层输入流中读取多个字节来填充byte数组,当程序读取一个或多个字节时,可直接从byte数组中获取,当内存中的byte读取完后,会再次用底层输入流填充缓冲区数组。

这种从直接内存中读取数据的方式要比每次都访问磁盘的效率高很多。下面通过分析源码,进一步理解其原理:

BufferedInputStream源码

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package java.io;  
  2. public class BufferedInputStream extends FilterInputStream {  
  3.       
  4.     //缓冲区数组默认大小8192Byte,也就是8M  
  5.     private static int defaultBufferSize = 8192;  
  6.     /** 
  7.      * 内部缓冲数组,会根据需要进行填充。 
  8.      * 大小默认为8192字节,也可以用构造函数自定义大小 
  9.      */  
  10.     protected volatile byte buf[];  
  11.     /**  
  12.      * 缓冲区中还没有读取的字节数 
  13.      * 当count=0时,说明缓冲区内容已读完,会再次填充 
  14.      */  
  15.     protected int count;  
  16.     // 缓冲区指针,记录缓冲区当前读取位置  
  17.     protected int pos;  
  18.     //真正读取字节的还是InputStream  
  19.     private InputStream getInIfOpen() throws IOException {  
  20.         InputStream input = in;  
  21.         if (input == null)  
  22.             throw new IOException("Stream closed");  
  23.         return input;  
  24.     }  
  25.     //创建空缓冲区  
  26.     private byte[] getBufIfOpen() throws IOException {  
  27.         byte[] buffer = buf;  
  28.         if (buffer == null)  
  29.             throw new IOException("Stream closed");  
  30.         return buffer;  
  31.     }  
  32.     //创建默认大小的BufferedInputStream  
  33.     public BufferedInputStream(InputStream in) {  
  34.         this(in, defaultBufferSize);  
  35.     }  
  36.     //此构造方法可以自定义缓冲区大小  
  37.     public BufferedInputStream(InputStream in, int size) {  
  38.         super(in);  
  39.         if (size <= 0) {  
  40.             throw new IllegalArgumentException("Buffer size <= 0");  
  41.         }  
  42.         buf = new byte[size];  
  43.     }  
  44.     /** 
  45.      * 填充缓冲区数组 
  46.      * 具体实现算法,可以看一下毕向东老师的视频,讲解的很详细, 
  47.      */  
  48.     private void fill() throws IOException {  
  49.         byte[] buffer = getBufIfOpen();  
  50.         if (markpos < 0)  
  51.             pos = 0;             
  52.         //....部分源码省略  
  53.         count = pos;  
  54.         int n = getInIfOpen().read(buffer, pos, buffer.length - pos);  
  55.         if (n > 0)  
  56.             count = n + pos;  
  57.     }  
  58.     /** 
  59.      * 读取一个字节 
  60.      * 与FileInputStream中的read()方法不同的是,这里是从缓冲区数组中读取了一个字节 
  61.      * 也就是直接从内存中获取的,效率远高于前者 
  62.      */  
  63.     public synchronized int read() throws IOException {  
  64.         if (pos >= count) {  
  65.             fill();  
  66.             if (pos >= count)  
  67.                 return -1;  
  68.         }  
  69.         return getBufIfOpen()[pos++] & 0xff;  
  70.     }  
  71.     //从缓冲区中一次读取多个字节  
  72.     private int read1(byte[] b, int off, int len) throws IOException {  
  73.         int avail = count - pos;  
  74.         if (avail <= 0) {  
  75.             if (len >= getBufIfOpen().length && markpos < 0) {  
  76.                 return getInIfOpen().read(b, off, len);  
  77.             }  
  78.             fill();  
  79.             avail = count - pos;  
  80.             if (avail <= 0return -1;  
  81.         }  
  82.         int cnt = (avail < len) ? avail : len;  
  83.         System.arraycopy(getBufIfOpen(), pos, b, off, cnt);  
  84.         pos += cnt;  
  85.         return cnt;  
  86.     }  
  87.   
  88.     public synchronized int read(byte b[], int off, int len){  
  89.         //为减少文章篇幅,源码就不显示了         
  90.     }  
  91. }  

最后我们通过一个实例更直观的说明BufferedStream的高效率。

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. import java.io.*;  
  2. /** 
  3.  * 分别用普通数据流和带缓冲区的数据流复制一个167M的数据文件 
  4.  * 通过用时比较两者的工作效率 
  5.  * @author Zues 
  6.  *  
  7.  */  
  8. public class CopyMp3 {  
  9.     private static File file = new File("D:\\1.mp4");  
  10.     private static File file_cp = new File("D:\\1_cp.mp4");  
  11.   
  12.     // FileInputStream复制  
  13.     public void copy() throws IOException {  
  14.         FileInputStream in = new FileInputStream(file);  
  15.         FileOutputStream out = new FileOutputStream(file_cp);  
  16.         byte[] buf = new byte[1024];  
  17.         int len = 0;  
  18.         while ((len = in.read(buf)) != -1) {  
  19.             out.write(buf);  
  20.         }  
  21.         in.close();  
  22.         out.close();  
  23.     }  
  24.     // BufferedStream复制  
  25.     public void copyByBuffer() throws IOException {  
  26.         BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));  
  27.         BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file_cp));  
  28.         byte[] buf = new byte[1024];  
  29.         int len;  
  30.         while ((len = in.read(buf)) != -1) {  
  31.             out.write(buf);  
  32.         }  
  33.         in.close();  
  34.         out.close();  
  35.     }  
  36.     public static void main(String[] args) throws IOException {  
  37.         CopyMp3 copy=new CopyMp3();  
  38.         long time1=System.currentTimeMillis();  
  39.         copy.copy();  
  40.         long time2=System.currentTimeMillis();  
  41.         System.out.println("直接复制用时:"+(time2-time1)+"毫秒");         
  42.         long time3=System.currentTimeMillis();  
  43.         copy.copyByBuffer();  
  44.         long time4=System.currentTimeMillis();  
  45.           
  46.         System.out.println("缓冲区复制用时:"+(time4-time3)+"毫秒");  
  47.     }  
  48. }  

当复制一段379M的视频文件时:

直接复制用时:3155毫秒

缓冲区复制用时:865毫秒

通过实验可以看出带缓冲区的数据流效率远远高于普通的数据流,而且操作的文件越大,优势越明显。

BufferedInputStream设计模式说明: 

这里用到了装设者设计模式,BufferedInputStream为装饰者类,FileInputStream为被装饰者类,前者的作用就是为了加强后者已有的功能,这里就是为了提高数据流的读写效率。

BufferedInputStream的构造方法定义:public BufferedInputStream(InputStream in)可以看出,Buffered可以装饰任何一个InputSteam的 子类。

【如有理解错误的地方,还望大神们指正,谢谢。】



关于read方法读取内容

1.没有markpos的情况很简单:


2有mark的情况比较复杂



0 0