NIO边看边记 之 FileChannel(七)

来源:互联网 发布:ios屏幕检测软件 编辑:程序博客网 时间:2024/06/05 05:49

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);
0 0