您的位置:首页 > Web前端

缓冲流-BufferedXXXXStream

2014-12-16 22:36 78 查看
BufferedOutputStream类将待写入的类存储到缓冲区(buf的保护字节数组字段)中,直到缓冲区满或刷新输出流。然后它将数据一次性写入底层输出流。

/**
* The internal buffer where data is stored.
*/
protected byte buf[];
BufferedInputStream类也有作为缓冲区的名为buf保护字节数组。当调用某个流的read方法时,它首先尝试从缓冲区获得请求的数据。只有当缓冲区没有数据时,流才会冲底层的源中读取。这时,它会尽可能多的从源中读取数据存入缓冲区。

两个类均有两个构造方法

/**
* Creates a new buffered output stream to write data to the
* specified underlying output stream.
*
* @param   out   the underlying output stream.
*/
public BufferedOutputStream(OutputStream out)
/**
     * Creates a new buffered output stream to write data to the 
     * specified underlying output stream with the specified buffer 
     * size. 
     *
     * @param   out    the underlying output stream.
     * @param   size   the buffer size.
     * @exception IllegalArgumentException if size <= 0.
     */
    public BufferedOutputStream(OutputStream out, int size)
/**
     * Creates a <code>BufferedInputStream</code>
     * and saves its  argument, the input stream
     * <code>in</code>, for later use. An internal
     * buffer array is created and  stored in <code>buf</code>.
     *
     * @param   in   the underlying input stream.
     */
    public BufferedInputStream(InputStream in)
/**
     * Creates a <code>BufferedInputStream</code>
     * with the specified buffer size,
     * and saves its  argument, the input stream
     * <code>in</code>, for later use.  An internal
     * buffer array of length  <code>size</code>
     * is created and stored in <code>buf</code>.
     *
     * @param   in     the underlying input stream.
     * @param   size   the buffer size.
     * @exception IllegalArgumentException if size <= 0.
     */
    public BufferedInputStream(InputStream in, int size) 
第一个参数是底层流,可以读取或者向其写入未缓冲的数据。如果给出第二个参数,则会指定缓冲区中的字节数量。

BufferedOutputStream类没有声明自己的新方法,只是覆盖了OutputStream类中的三个方法:

public synchronized void write(int b) throws IOException;
public synchronized void write(byte b[], int off, int len) throws IOException;
public synchronized void flush() throws IOException
调用这些方法,每次写入会把数据放在缓冲区,而不是直接放在底层的输出流。因此,在数据需要发送时刷新输出流是很重要的。

BufferedInputStream类也没有声明新的方法,只是覆盖了InputStream类中的方法。

public synchronized int read() throws IOException;
public synchronized int read(byte b[], int off, int len) throws IOException;
public synchronized long skip(long n) throws IOException ;
public synchronized int available() throws IOException ;
public synchronized void mark(int readlimit);
public synchronized void reset() throws IOException;
public boolean markSupported();
public void close() throws IOException
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: