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

NIO边看边记 之 FileChannel(七)

2016-05-04 21:23 302 查看
FileChannel不可工作在非阻塞模式,不可以将FileChannel注册到Selector上。

1.打开

FileChannel不能直接打开,需要通过一个与之关联的FileInputStream、FileOutputStream或者RandomAccessFile来获得FilChannel。

如:

RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "rw");
FileChannel fileChannel = randomAccessFile.getChannel();


2.读数据

从FileChannel中读取数据到buffer中,返回可以读取的字节数。如果到达文件末尾,则返回-1

ByteBuffer buffer = ByteBuffer.allocate(48);
int readBytes = fileChannel.read(buffer);


3.写数据

可以将buffer中的内容写到channel中。

buffer.flip()
while(buffer.hasRemaining()) {
fileChannel.write(buffer);
}


注意从buffer中读取数据写到channel中时,需要调用flip方法来切换buffer的读写模式。

调用write时无法保证能向channel中写入多少字节,因此需要循环

4.关闭

fileChannel.close();


5.size

通过FileChannel可以得到与之相关联的File的大小。

fileChannel.size()


6.截断

可以通过truncate方法来截取文件。

fileChannel.truncate(1024);


则只保留文件中前1024个字节的内容,文件中指定长度后面的内容将被清空。

7.force()

将buffer中的内容写到channel时,并没有直接写到文件中,而是存在了内存中。如果要实时写到硬盘上,则要调用force()方法。

force()方法有一个boolean类型的参数,指明是否同时将文件元数据(权限信息等)写到磁盘上。

fileChannel.force(true);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java nio FileChanne