FileChannel的基本使用实例



FileChannel的基本使用实例,FileChannel用法实例,FileChannel如何使用,FileChannel,是内存与磁盘文件的通道。

========================================================

FileChannel优势:

  • 多线程并发读写,并发性;
  • IO读写性能提高(OS负责),也可引做共享内存,减少IO操作,提升并发性;
  • 应用crash,保证这部分内容还能写的进去文件。在我们调用channel.write(bytebuffer)之后,具体何时写入磁盘、bytebuffer中内容暂存于哪里(os cache)等相关一系列问题,就交由OS本身负责了。

========================================================

FileChannel的方法:

  • read(),write()
  • lock(), tryLock()
  • position(), size(), truncate()
  • transferFrom(), transferTo()
  • map()

package com.taobao.nio.channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
* FileChannel的基本使用。
*/
public class AcquireChannel {
public static void main(String[] args) throws Exception {
// 根据FileOutputStream获得通道FileChannel
FileChannel channel = new FileOutputStream(“D:/a.txt”).getChannel();
// 字节方式写入
channel.write(ByteBuffer.wrap(“hello, NIO world in java!”.getBytes()));
channel.close();

// 根据FileInputStream获得通道FileChannel
channel = new FileInputStream(“D:/a.txt”).getChannel();
// ByteBuffer分配空间,16个字节
// 这里需要知道 byte是1字节, short和char是2字节,int和float是4字节
// long和double是8字节 1byte=8bit 。 基本只是还是必须记住的。
ByteBuffer buff = ByteBuffer.allocate(16);
// 字节数组数据装入buff,
channel.read(buff);
// 反转此缓冲区
buff.flip();
// 逐个输出,因为分配了16,所以输出的时候只能输出hello, NIO world,剩下的
// 因为空间关系被截断。
while(buff.hasRemaining()){
System.out.print((char)buff.get());
}
channel.close();
}
}