OutputStream
OutputStream
1 | public abstract class OutputStream implements Closeable, Flushable{ |
ByteArrayOutputStream
这个类内部持有一个字节数据,write 方法就是将字节数据写入到该字节数据中。注意底层的 ByteArray 会随着不断的 write 而增大,所以底层的 Array 是无限大的。当然一旦写入的数据个数超过:Integer.MAX_VALUE,则OutOfMemoryError()。
1 |
|
buf
存储字节数据
count
buf 中写入的有效字节个数
FileOutputStream
这个类的实现可以参考 openjdk1.7 的实现。
构造函数
1 | public FileOutputStream(File file, boolean append) |
open 的实现
open 的实现在 jdk 中
1 | // src/solaris/native/java/io |
JVM_Open 方法在 jvm 的实现中。
1 | // src/share/vm/prims/jvm.cpp |
write 过程
1 |
|
close 过程
1 | void |
close() closes a file descriptor, so that it no longer refers to any file and may be reused. Any record locks (see fcntl(2)) held on the file it was associated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock).
If fd is the last file descriptor referring to the underlying open file description (see open(2)), the resources associated with the open file description are freed; if the descriptor was the last reference to a file which has been removed using unlink(2) the file is deleted.
以上引用来自,linux 对 close 方法的描述,可以看到 close 方法的重要性,所以当流使用完毕一定要及时关闭。否则,底层的文件将一直被占用,无法释放,造成了资源的浪费。
BufferedOutputStream
1 | public class BufferedOutputStream extends FilterOutputStream{ |
内部持有一个默认的 8K 的缓冲区 buf, write 操作优先写入这个buffer. 直到 buf 满了,调用 flushBuffer 将缓冲区内部的数据写入到底层的流中。