kevinlinxp
6/7/2017 - 7:04 AM

Java:NIO

Java:NIO

-- 普通读写 --
ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
while(in.read(buffer)!= -1) {
  buffer.flip(); // Prepare for writing
  out.write(buffer);
  buffer.clear(); // Prepare for reading;
}

// read 之前 buffer.clear();
// write 之前 buffer.flip();
// 准备重新处理时rewind();

缓冲器容纳的是普通的字节,为了把它们转换成字符,我们要么在输入它们的时候对其进行编码(这样,它们输出时才具有意谓),要么在将其从缓冲器输出时对它们进行解码。可以使用java.nio.charset.Charset类实现这些功能:
CharBuffer - Charset.forName(encoding).decode(buff)

-- 视图 --
// Store and read a char array:
bb.asCharBuffer().put("Howdy!");
char c;
while((c = bb.getChar()) != 0) {
  System.out.print(c);
}
System.out.println();
bb.rewind();

// Store and read a short:
bb.asShortBuffer().put((short)471142);
System.out.println(bb.getShort());
bb.rewind();

// Store and read a int:
bb.asIntBuffer().put(99471142);
System.out.println(bb.getInt());
bb.rewind();

// Store and read a long:
bb.asLongBuffer().put(99471142);
System.out.println(bb.getLong());
bb.rewind();

//Store and read a float:
bb.asFloatBuffer().put(99471142);
System.out.println(bb.getFloat());
bb.rewind();

// Store and read a double:
bb.asDoubleBuffer().put(99471142);
System.out.println(bb.getDouble());
bb.rewind();

-- (视图时)高低位 --
bb.order(ByteOrder.BIG_ENDIAN); -- 默认的,重要字节放低位:'a' - 00000000 01100001
bb.order(ByteOrder.LITTLE_ENDIAN); -- 相反 'a' - 01100001 00000000

-- mark(), reset()用法 --
private static void symmetricScramble(CharBuffer buffer){
  while(buffer.hasRemaining()) {
    buffer.mark();
    char c1 = buffer.get();
    char c2 = buffer.get();
    buffer.reset();
    buffer.put(c2).put(c1);
  }
}

-- 映射文件 --
public static void main(String[] args) throws Exception{
  MappedByteBuffer mbb = new RandomAccessFile("test.dat","rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, length);

  for(int i = 0; i<length; i++) {
    mbb.put((byte)'x');
  }

  System.out.println("finished writing");

  for(int i = length/2; i<length/2 + 6; i++) {
    System.out.println((char)mbb.get(i));
  }
}