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

  • 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;
      }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值