1/** 2 * 大多数操作系统可以利用虚拟内存将文件或文件一部分映射到内存中,然后这个文件就可以被当做内存数组一样被访问;避免底层IO的开销<p> 3 * 【通道】是一种用于磁盘文件的一种抽象;<br> 4 * 它使我们可以访问诸如内存映射,文件加锁机制以及文件间快速数据传递等特性; 5*@date:2018年7月5日 6*@author:zhangfs 7 8 9*/ 10public class GetChannel { 11 12 private static final int BSIZE=1024; 13 public static void main(String[] args) throws IOException { 14 15 //写 16 FileChannel fileChannel=new FileOutputStream("data.txt").getChannel(); 17 fileChannel.write( ByteBuffer.wrap("hello".getBytes()));//warp将已存在的数组包装到butebuffer中; 18 fileChannel.close(); 19 //可读可写 20 fileChannel=new RandomAccessFile("data.txt", "rw").getChannel(); 21 fileChannel.position(fileChannel.size());//移动到filechannel最后 22 fileChannel.write(ByteBuffer.wrap(" world".getBytes())); 23 fileChannel.close(); 24 //读 25 fileChannel=new FileInputStream("data.txt").getChannel(); 26 ByteBuffer buffer=ByteBuffer.allocate(BSIZE); 27 fileChannel.read(buffer); 28 buffer.flip();//让别人读取字符的准备;有利于获取最大速度 29 while(buffer.hasRemaining()) { 30 printnb((char)buffer.get()); 31 } 32 33 } 34}
javaNio 通道和缓冲区
Wesley13
2021-10-11
1155 1 0
点赞
收藏
评论区
加载中...