<span style="font-family: Arial; background-color: rgb(255, 255, 255);">DataOutputStream 类与BufferedOutputStream类的区别是什么:</span>
BufferedOutputStream类能够在内存里建立一个缓冲区,当写文件的时候,能起到缓冲的作用.但是DataOutputStream能像BufferedOutputStream类一样起到缓冲作用吗?如果有缓冲作用的话,但是DataOutputStream 类的构造函数里,只有一个.而且其构造函数的参数没有提供出设置缓存大小的参数?
BufferedOutputStream类中构造对此类这样定义:
<pre name="code" class="java"> /**
* Constructs a new {@code BufferedOutputStream}, providing {@code out} with a buffer
* of 8192 bytes.
*
* @param out the {@code OutputStream} the buffer writes to.
*/
public BufferedOutputStream(OutputStream out) {
this(out, 8192);
}
/**
* Constructs a new {@code BufferedOutputStream}, providing {@code out} with {@code size} bytes
* of buffer.
*
* @param out the {@code OutputStream} the buffer writes to.
* @param size the size of buffer in bytes.
* @throws IllegalArgumentException if {@code size <= 0}.
*/
public BufferedOutputStream(OutputStream out, int size) {
super(out);
if (size <= 0) {
throw new IllegalArgumentException("size <= 0");
}
buf = new byte[size];
}
代码是这样定义,当缓冲区的数据达到8192时候,才会对缓冲区进行flush()操作,如果没有达到该大小,手动调用flush()才会成功!
<span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;">DataOutputStream 类中是这样构造定义:</span>
<span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;"> /**
* Constructs a new {@code DataOutputStream} on the {@code OutputStream}
* {@code out}. Note that data written by this stream is not in a human
* readable form but can be reconstructed by using a {@link DataInputStream}
* on the resulting output.
*
* @param out
* the target stream for writing.
*/
public DataOutputStream(OutputStream out) {
super(out);
}
</span>
没有定义缓冲区的大小,也就是说缓冲区只要有数据都会flush()出来。
所以在常规情况下,
需要注意的是,如果采用什么样的流写,必须采用对应的流读。
为了能够提高读写效率,一次性把数据写、读。采用DataOutputStream。
针对file的写、读,使用DataOutputStream装饰FileOutputStream;
针对byte的写读,使用DataOutputStream装饰ByteArrayOutputStream。