• 【原创】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;

  • 相关阅读:
    enter事件处方方法
    vue 关于父组件无法触发子组件的事件的解决方法
    iview表格高度自适应只需要三步即可
    子组件触发父组件的方法
    组件之间的方法
    年与日时分秒各种格式 补0位的方法
    //定义一个函数,删除首个数组元素
    input标签内容改变的触发事件
    jQuery表单校验jquery.validate.js的使用
    jQuery BlockUI 实现锁屏
  • 原文地址:https://www.cnblogs.com/earendil/p/5016008.html
Copyright © 2020-2023  润新知