1、ByteBuffer類型化的put與get方法java
/** * ByteBuffer類型化的put與get方法 */ public class NioTest5 { public static void main(String[] args) { ByteBuffer buffer = ByteBuffer.allocate(64); buffer.putInt(5); buffer.putLong(500000000L); buffer.putDouble(13.456); buffer.putChar('你'); buffer.putShort((short) 3); buffer.flip(); System.out.println(buffer.getInt()); System.out.println(buffer.getLong()); System.out.println(buffer.getDouble()); System.out.println(buffer.getChar()); System.out.println(buffer.getShort()); } }
put和get的類型要一致。如第一個是putInt, 輸出的使用第一個要用getInt。數組
2、Slice Bufferblog
/** * Slice Buffer和原Buffer共享底層數組,任一一個改變,另一個也會改變 */ public class NioTest6 { public static void main(String[] args) { ByteBuffer buffer = ByteBuffer.allocate(10); for(int i = 0; i < buffer.capacity(); ++i){ buffer.put((byte)i); } buffer.position(2); buffer.limit(6); ByteBuffer sliceBuffer = buffer.slice(); for(int i = 0; i < sliceBuffer.capacity(); ++i){ byte b = sliceBuffer.get(i); b *= 2; sliceBuffer.put(i, b); } buffer.position(0); buffer.limit(buffer.capacity()); while (buffer.hasRemaining()){ System.out.println(buffer.get()); } } }
3、只讀Bufferip
/** * 只讀buffer,咱們能夠隨時將一個普通Buffer調用asReadOnlyBuffer方法返回一個只讀Buffer * 但不能將一個只讀Buffer轉換爲讀寫Buffer */ public class NioTest7 { public static void main(String[] args) { ByteBuffer buffer = ByteBuffer.allocate(10); System.out.println(buffer.getClass()); for(int i = 0; i < buffer.capacity(); ++i){ buffer.put((byte)i); } ByteBuffer readonlyBuffer = buffer.asReadOnlyBuffer(); System.out.println(readonlyBuffer.getClass()); readonlyBuffer.position(0); readonlyBuffer.put((byte)2); } }
對只讀Buffer進行修改,將拋出異常ci