by shihang.mai
1. 普通I/O
I/O buffer为什么比普通的FileOutPutStram块:
首先明白,用户态内核态切换需要中断。buffer每8k做一次system call write,而普通的IO是每一次都system call write。比buffer多很多次中断。
2. 文件IO
2.1 bytebuffer
buffer.compact();会压缩剩下的元素
public static void whatByteBuffer(){
//堆内分配
ByteBuffer buffer = ByteBuffer.allocate(1024);
//堆外分配
//ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
System.out.println("postition: " + buffer.position());
System.out.println("limit: " + buffer.limit());
System.out.println("capacity: " + buffer.capacity());
System.out.println("mark: " + buffer);
buffer.put("123".getBytes());
System.out.println("-------------put:123......");
System.out.println("mark: " + buffer);
buffer.flip(); //读写交替
System.out.println("-------------flip......");
System.out.println("mark: " + buffer);
buffer.get();
System.out.println("-------------get......");
System.out.println("mark: " + buffer);
buffer.compact();
System.out.println("-------------compact......");
System.out.println("mark: " + buffer);
buffer.clear();
System.out.println("-------------clear......");
System.out.println("mark: " + buffer);
}

2.2 MappedByteBuffer
public static void testRandomAccessFileWrite() throws Exception {
RandomAccessFile raf = new RandomAccessFile(path, "rw");
raf.write("hello mashihang\n".getBytes());
raf.write("hello yoko\n".getBytes());
System.out.println("write------------");
System.in.read();
raf.seek(4);
raf.write("ooxx".getBytes());
System.out.println("seek---------");
System.in.read();
FileChannel rafchannel = raf.getChannel();
//system call mmap 位置:堆外 和文件映射的 byte
MappedByteBuffer map = rafchannel.map(FileChannel.MapMode.READ_WRITE, 0, 4096);
/*
* 不是系统调用 但是数据会到达 内核的pagecache
* 曾经我们是需要out.write() 这样的系统调用,才能让程序的data 进入内核的pagecache,必须有用户态内核态切换
*/
map.put("@@@".getBytes());
System.out.println("map--put--------");
System.in.read();
// flush
//map.force();
raf.seek(0);
ByteBuffer buffer = ByteBuffer.allocate(8192);
// ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
rafchannel.read(buffer); //buffer.put()
System.out.println(buffer);
buffer.flip();
System.out.println(buffer);
for (int i = 0; i < buffer.limit(); i++) {
Thread.sleep(200);
System.out.print(((char)buffer.get(i)));
}
}

网友评论