Java NIO——2 缓冲区
一、缓冲区基础1、缓冲区并不是多线程安全的。2、属性(容量、上界、位置、标记)capacitylimit 第一个不能被读或写的元素position 下一个要被读或写的元素索引mark 一个备忘位置3、方法操作(1)翻转buffer.flip() 等同于 buffer.limit(buffer.position()).position(0)(2)、释放buffer.flip();for(int i=0; buffer.hasRemaining(); i++){ myByteArray[i] = buffer.get();
}
public class Unsigned { public static short getUnsignedByte (ByteBuffer bb) { return ((short)(bb.get( ) & 0xff)); } public static void putUnsignedByte (ByteBuffer bb, int value) { bb.put ((byte)(value & 0xff)); } public static short getUnsignedByte (ByteBuffer bb, int position) { return ((short)(bb.get (position) & (short)0xff)); } public static void putUnsignedByte (ByteBuffer bb, int position, int value) { bb.put (position, (byte)(value & 0xff)); } // --------------------------- public static int getUnsignedShort (ByteBuffer bb) { return (bb.getShort( ) & 0xffff); } public static void putUnsignedShort (ByteBuffer bb, int value) { bb.putShort ((short)(value & 0xffff)); } public static int getUnsignedShort (ByteBuffer bb, int position) { return (bb.getShort (position) & 0xffff); } public static void putUnsignedShort (ByteBuffer bb, int position, int value) { bb.putShort (position, (short)(value & 0xffff)); } // --------------------------- public static long getUnsignedInt (ByteBuffer bb) { return ((long)bb.getInt( ) & 0xffffffffL); } public static void putUnsignedInt (ByteBuffer bb, long value) { bb.putInt ((int)(value & 0xffffffffL)); } public static long getUnsignedInt (ByteBuffer bb, int position) { return ((long)bb.getInt (position) & 0xffffffffL); } public static void putUnsignedInt (ByteBuffer bb, int position, long value) { bb.putInt (position, (int)(value & 0xffffffffL)); } }
6、内存映射缓冲区映射缓冲区是带有存储在文件,通过内存映射来存取数据元素的字节缓冲区。映射缓冲区通常是直接存取内存的,只能通过 FileChannel 类创建。