1.文件复制
public static void method6() throws IOException {
try {
FileInputStream fis = new FileInputStream("D:\\var\\demo.txt");
FileOutputStream fos = new FileOutputStream("D:\\var\\demo3.txt");
FileChannel readChannel = fis.getChannel();
FileChannel writerChannel = fos.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(0124);
while(true) {
buffer.clear();
int len = readChannel.read(buffer);
if(len == -1)
break;
buffer.flip();
writerChannel.write(buffer);
}
readChannel.close();
writerChannel.close();
System.out.println("over");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2.buffer的创建的两种方式
ByteBuffer buffer1 = ByteBuffer.allocate(0124);
byte[] arr = new byte[1024];
ByteBuffer buffer2 = ByteBuffer.wrap(arr);
3.buffer重置
rewind() | clear() | flip() | |
---|---|---|---|
position | 置零 | 置零 | 置零 |
mark | 清空 | 清空 | 清空 |
limit | 未改动 | 设置为capacity | 设置为position |
作用 | 为读取buffer中有效数据做准备 | 为重新写入buffer做准备 | 在读写切换时调用 |
4.读写缓冲区
5.标志缓冲区
6.复制缓冲区
7.缓冲区分片
8.只读缓冲区
9.文件映射到内存
public static void method7() throws IOException {
RandomAccessFile raf = new RandomAccessFile("D:\\\\var\\\\demo.txt", "rw");
FileChannel fc = raf.getChannel();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, raf.length());
while(mbb.hasRemaining())
System.out.println((char)mbb.get());
}
10.处理结构化数据
11.直接内存访问
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);