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;
      }
}
相關文章
相關標籤/搜索