学习 NIO ,NIO 中 buffer 和 channel 的基本用法
程序员文章站
2022-04-24 11:05:47
...
这篇博客为个人学习小结,因此不大注重博客的美观。
文件流.getChannel()
fileChannel 将buffer的数据写入文件
fileChannel 将文件的数据读入buffer
拷贝
fileChannel1将文件的数据读入buffer
fileChannel2将buffer的数据写入文件
两个fileChannel之间传输文件
targetChannel.transferFrom(sourceChannel,0,sourceChannel.size());
或
sourceChannel.transferTo(0,sourceChannel.size(),targetChannel);
byteBuffer 可以类型化的读取
byteBuffer.putInt(123);
byteBuffer.putDouble(6.66);
byteBuffer.flip();
byteBuffer.getInt(123);
byteBuffer.getDouble(6.66);
按顺序读取,顺序错误则数据错误
如果越界,报异常
BufferUnderflowException
可以转为只读buffer
byteBuffer.asReadOnlyBuffer();
在堆外内存修改文件,配置映射,NIO完成文件的同步
new RandomAccessFile("1.txt", "rw").getChannel();
randomAccessFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 5);
mappedByteBuffer.put(0,(byte) 'H');
randomAccessFile.close();
byteBuffer 常用方法
ByteBuffer.allocate(5);
byteBuffer.capacity();
byteBuffer.position();
byteBuffer.limit();
byteBuffer.flip();
byteBuffer.clear();
channel的read和write支持buffer数组
上一篇: java简单NIO操作文件示例(写、读、复制文件)
下一篇: JPA之JPA中的多对多双向关联