try (FileChannel channel = new FileInputStream("stu.txt").getChannel()){
//给缓冲区 分配空间
ByteBuffer buffer = ByteBuffer.allocate(10);
int read = 0 ;
StringBuilder builder = new StringBuilder();
while ((read =channel.read(buffer))>0){
//切换成 读模式 limit = position; position=0
buffer.flip();
while (buffer.hasRemaining()){
builder.append((char)buffer.get());
}
//清空字节数组 切换成 写模式 position=0 ;limit = capacity
buffer.clear();
}
System.out.println(builder.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
复制代码
打印结果:
0123456789abcdef
复制代码
核心属性
字节缓冲区的父类 Buffer 中有几个核心属性,如下
[code]// Invariants: mark > 4]; private static final String[] BYTE2HEX = new String[256]; private static final String[] BYTEPADDING = new String[16]; static { final char[] DIGITS = "0123456789abcdef".toCharArray(); for (int i = 0; i < 256; i++) { HEXDUMP_TABLE[i >> 4 & 0x0F]; HEXDUMP_TABLE[(i > 4; final int remainder = length & 0xF; // Dump the rows which have 16 bytes. for (int row = 0; row < fullRows; row++) { int rowStartIndex = (row