【原创】java NIO FileChannel 学习笔记 FileChannel 简介

java NIO 中FileChannel 的实现类是  FileChannelImpl,FileChannel本身是一个抽象类。

先介绍FileChannel

  File Channels 是线程安全的。Channel的close方法可以随时执行(正如Channel接口所要求的)。任何企图修改filechannel 对应文件大小 或者修改 filechannel position的操作都必须串行执行,第二个操作会一直阻塞直到前一个运行完。不过这些方法,具体还要看如何实现。(下文分析FileChannelImpl)。

  创建FileChannel 实例可以通过执行FileChannel的一些方法,比如open方法,或者通过java.io.FileInputStream、java.io.FileOutputStream、java.io.RandomAccessFile的getchannel() 。(ps:网上说RandomAccessFile默认就获取了文件锁,但是我在官网api和RandomAccessFile.java中并未发现相关说明和代码,有人知道是怎么回事的话望不吝赐教,目前我对网上的观点持怀疑态度。)如果使用getChannel获取的FileChannel的话,FileChannel就与FileInputStream或FileOutputStream等对象,产生了关联(后文在分析为何会这样)。也就是说比如当前新建一个FileInputStream对象,然后获取一个FileChannel,此时position是0,然后FileInputStream读取了100字节,读完之后,FIleInputStream下次肯定会从第101个字节读取,这是显而易见的,但是你刚才获取的Channel的position也会移动100。有代码为证:

FileInputStream inputstream = new FileInputStream(sourceFile);
byte[] buffer = new byte[100];
ByteBuffer bb = ByteBuffer.allocate(1024);
FileChannel channel = inputstream.getChannel();
System.out.println("channel "+channel.position());
int read=inputstream.read(buffer);
System.out.println("channel "+channel.position()+" read "+read);

输出结果:

channel 0
channel 100 read 100

继续。FileChannel打开模式有 读、写 和 读and写。FileInputStream获取的自然是读.OutputStream自然是写,RandomAccessFile就看你的RandomAccessFile是何种模式。

FileChannel的追加模式(append-mode)是由所使用的FileOutputStream决定的。追加模式时先跳到文件末尾再开始写,这个操作的原子性是由操作系统支持(FileChannel.java 中的原文 Whether the advancement of the position and the writing of the data are done in a single atomic operation is system-dependent and therefore unspecified)。

posted @ 2015-12-03 11:17  Earendil  阅读(2740)  评论(0编辑  收藏  举报