FileChannel 可由 RandomAccessFile、FileOutputStream 等 getChannel方法获取
RandomAccessFile raf = new RandomAccessFile("d://test.txt", "rws");
FileChannel channel = raf.getChannel();
ByteBuffer bb = ByteBuffer.allocate(20); //或 ByteBuffer.wrap(byte[] array);
bb.put("123456".getBytes("UTF-8"));//ByteBuffer的position 移动到 12位置
bb.flip();//ByteBuffer的position设置到 0 如果没有flip操作,下文中的write将只会读取bb 位置大于12至20之间的未知字节信息放入到文件中
channel.write(bb);//当前文件指针在文件的开始位置,那么读取bb中的所有20个字节 覆盖文件中前20个字节内容.
channel.write(ByteBuffer.wrap("ABCDEFG".getBytes()));//position为0
FileChannel 的 read(ByteBuffer) 操作 将 FileChannel中数据读取到 ByteBuffer中 , 读取的内容由当前文件指针位置决定, 放入ByteBuffer的位置由ByteBuffer当前空置的position值决定
FileChannel 的 write(ByteBuffer) 操作 将ByteBuffer中数据写入到FileChannel中,读取的内容由当前ByteBuffer的position位置决定,放入的位置由当情文件指针所处位置决定
JAVA 的字符编码为 UNICODE , 字符占2个字节.
”123“.getBytes().length 获取的长度为 3, 默认为外编码 UTF-8
"123".getBytes("unicode").length 获取的长度为 8