mark:标记,用于需要记录position的位置。
2. 缓冲区的核心方法:
String str = "abcdef";
ByteBuffer b = ByteBuffer.allocate(1024);
System.out.println(b.isDirect());
b.put(str.getBytes());
System.out.println("------------------");
System.out.println("capacity: "+b.capacity());
System.out.println("limit: "+b.limit());
System.out.println("position: "+b.position());
System.out.println("---------flip---------");
b.flip();//切换读取,否则读取不出
System.out.println("capacity: "+b.capacity());
System.out.println("limit: "+b.limit());
System.out.println("position: "+b.position());
System.out.println("---------get---------");
byte[] byt = new byte[b.limit()];
b.get(byt);//获取
System.out.println(""+new String(byt));
System.out.println("capacity: "+b.capacity());
System.out.println("limit: "+b.limit());
System.out.println("position: "+b.position());
System.out.println("---------rewind---------");
b.rewind();//重读
System.out.println("capacity: "+b.capacity());
System.out.println("limit: "+b.limit());
System.out.println("position: "+b.position());
System.out.println("---------clear---------");
b.clear();//回到原始状态,但并没有清空数据,数据处于被遗忘状态
System.out.println("capacity: "+b.capacity());
System.out.println("limit: "+b.limit());
System.out.println("position: "+b.position());
FileChannel reader = FileChannel.open(Paths.get("D:/c.jpg"), StandardOpenOption.READ);
FileChannel writer = FileChannel.open(Paths.get("D:/c3.jpg"), StandardOpenOption.WRITE,StandardOpenOption.READ, StandardOpenOption.CREATE);
MappedByteBuffer inMapper = reader.map(MapMode.READ_ONLY, 0, reader.size());
MappedByteBuffer outMapper = writer.map(MapMode.READ_WRITE, 0, reader.size());
byte[] bye = new byte[inMapper.limit()];
inMapper.get(bye);
outMapper.put(bye);
reader.close();
writer.close();
FileChannel inChannel = FileChannel.open(Paths.get("D:/a.avi"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("D:/a1.avi"), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
inChannel.transferTo(0, inChannel.size(), outChannel);
outChannel.close();
inChannel.close();
分散(Scatter)与聚集(Gather)
(图一、分散读取) (图二、聚集写入)
FileChannel reader = input.getChannel();
FileChannel writer = output.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
ByteBuffer buffer1 = ByteBuffer.allocate(2024);
ByteBuffer[] buffers = new ByteBuffer[]{buffer,buffer1};
reader.read(buffers);//分散读取
writer.write(buffers);//聚集写入