zoukankan      html  css  js  c++  java
  • 【原创】java NIO FileChannel 学习笔记 新建一个FileChannel

     首先使用FileChannel 的open方法获取一个FileChannel对象。下面这段代码是FileChannel中open方法的代码。

    public static FileChannel open(Path path,
    Set<? extends OpenOption> options,
    FileAttribute<?>... attrs)
    throws IOException
    {
    FileSystemProvider provider = path.getFileSystem().provider();
    return provider.newFileChannel(path, options, attrs);
    }

    private static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0];

    public static FileChannel open(Path path, OpenOption... options)
    throws IOException
    {
    Set<OpenOption> set = new HashSet<OpenOption>(options.length);
    Collections.addAll(set, options);
    return open(path, set, NO_ATTRIBUTES);
    }

     然后对代码进行介绍(其实就是翻译了源代码的注释而已)。首先介绍参数options,OpenOption以StandardOpenOption为例进行介绍

        public enum StandardOpenOption implements OpenOption 

    该枚举(StandardOpenOption)包括READ、 WRITE、 APPEND、 CREATE 、CREATE_NEW、 DELETE_ON_CLOSE、TRUNCATE_EXISTING还有SYNC     DSYNC

    区别在于SYNC除了会将跟新的文件内容同步到存储设备上之外,还会同步更新文件的元数据。

    InputStream 或者OutputSteam获取Channel的get方法

    一下以FileOutputStream为例:

    public FileChannel getChannel() {
    synchronized (this) {
    if (channel == null) {
    channel = FileChannelImpl.open(fd, path, false, true, append, this);
    }
    return channel;
    }
    }

    代码分析 fd是FileDescriptor,在FileOutputStream中有 private FileChannel channel;

  • 相关阅读:
    Python学习
    我的计算机网络复习笔记(第一章)
    理解DES算法
    彻底理解RSA加密算法
    扩展欧几里得算法求模的乘法逆元
    python的deque(双向)队列详解
    对于暴力枚举的一些优化方法的题解
    python中的多(liu)元(mang)交换 ,赋值
    python定义函数后跟->的意义
    直接暴力做分糖问题
  • 原文地址:https://www.cnblogs.com/earendil/p/5016008.html
Copyright © 2011-2022 走看看