FileOutputStream 是继承与OutputStream的子类
1 常用属性
- private final FileDescriptor fd;// 文件描述符
- private final boolean append; // 是否在文件尾部开始追加写入
- private FileChannel channel; // 用于读、写、映射、操作文件的通道
- private final String path;// 文件的路径
- private final Object closeLock = new Object();// 一个关闭锁,只在close()方法中使用,确保多线程同步调用
2 构造函数
- public FileOutputStream(String name);// 创建一个向指定File对应的文件中写入数据的文件输出流
- public FileOutputStream(String name, boolean append);// 创建一个向指定File对应的文件中写入数据的文件输出流,第二个参数append是否在文件末尾开始写入
- public FileOutputStream(File file);// 创建一个向指定File对应的文件中写入数据的文件输出流
- public FileOutputStream(File file, boolean append);// 创建一个向指定File对应的文件中写入数据的文件输出流
- public FileOutputStream(FileDescriptor fdObj); // 根据文件描述符构造输出流
3 常用方法
// 写入一个字节到该文件输出流中,调用下边的本地方法
-
public void write(int b) throws IOException {
write(b, append);// 调用的是一个native方法
}
// 本地方法,写入一个字节到该文件输出流中
- private native void write(int b, boolean append) throws IOException;
// 将给定的字节数组b中的所有字节写入文件输出流,调用本地方法
-
public void write(byte b[]) throws IOException {
writeBytes(b, 0, b.length, append);
}
// 将给定的字节数组b中从off开始的len个字节字节写入文件输出流,调用下边的本地方法
-
public void write(byte b[], int off, int len) throws IOException {
writeBytes(b, off, len, append);
}
// 本地方法,将给定的字节数组b中从off开始的len个字节写入文件输出流
- private native void writeBytes(byte b[], int off, int len, boolean append) throws IOException;
// 关闭流,调用本地的方法
-
public void close() throws IOException {
synchronized (closeLock) { if (closed) { return; } closed = true; } if (channel != null) { channel.close(); } fd.closeAll(new Closeable() { public void close() throws IOException { close0(); } });
}
// 本地方法,关闭流
- private native void close0() throws IOException;
// 清理到文件的连接,并确保不再引用此文件输入流时调用此close的方法
-
protected void finalize() throws IOException {
if (fd != null) { if (fd == FileDescriptor.out || fd == FileDescriptor.err) { flush(); } else { close(); } }
}
// 获取流对象对应的通道,如果为空就创建一个新的通道
-
public FileChannel getChannel() {
synchronized (this) { if (channel == null) { channel = FileChannelImpl.open(fd, path, false, true, append, this); } return channel;}
-
}