Java IO框架总揽--FileOutputStream源码解读

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 构造函数app

  • 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 {this

    write(b, append);// 调用的是一个native方法

    }线程

    // 本地方法,写入一个字节到该文件输出流中code

  • private native void write(int b, boolean append) throws IOException;

// 将给定的字节数组b中的全部字节写入文件输出流,调用本地方法对象

  • public void write(byte b[]) throws IOException {继承

    writeBytes(b, 0, b.length, append);

    }ip

// 将给定的字节数组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;
      }
}
相关文章
相关标签/搜索