您的位置:首页 > 编程语言 > Java开发

【原创】java NIO FileChannel 学习笔记 新建一个FileChannel

2015-12-03 13:51 549 查看
首先使用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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: