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

 

转载于:https://www.cnblogs.com/earendil/p/5016008.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值