java nio的基础--缓冲区
有一本小书,叫<java nio>, 2002年的中文版PDF。 可以看看,尽管是一本历史感很强的书, 讲解还是很细致的。 由此进深入nio2的话, 那java io的秘密, 就全部清晰了。 package com.ronsoft.books.nio.buffers; import java.nio.CharBuffer; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class BufferFillDrain { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub CharBuffer buffer = CharBuffer.allocate(100); while (fillBuffer(buffer)) { buffer.flip(); drainBuffer(buffer); buffer.clear(); } ByteBuffer byteBuffer = ByteBuffer.allocate(7).order(ByteOrder.BIG_ENDIAN); CharBuffer charBuffer = byteBuffer.asCharBuffer(); byteBuffer.put(0, (byte)0); byteBuffer.put(1, (byte)'H'); byteBuffer.put(2, (byte)0); byteBuffer.put(3, (byte)'i'); byteBuffer.put(4, (byte)0); byteBuffer.put(5, (byte)'!'); byteBuffer.put(6, (byte)0); println(byteBuffer); println(charBuffer); } private static void drainBuffer(CharBuffer buffer) { while (buffer.hasRemaining()) { System.out.print(buffer.get()); } System.out.println(""); } private static boolean fillBuffer(CharBuffer buffer) { if (index >= strings.length) { return (false); } String string = strings[index++]; for (int i = 0; i < string.length(); i++) { buffer.put(string.charAt(i)); } return (true); } private static int index = 0; private static String []strings = { "A random string value", "The product of an infinite number of monkeys", "Hey hey we're the Monkees", "Opening act for the Monkees: Jimi Hendrix", "'Scuse me while I kill this fly", "Help Me! Help Me!", }; private static void println(Buffer buffer) { System.out.println("post=" + buffer.position() + ", limit=" + buffer.limit() + ", capacity=" + buffer.capacity() + ": '" + buffer.toString() + "'"); } } 输出如下: A random string value The product of an infinite number of monkeys Hey hey we're the Monkees Opening act for the Monkees: Jimi Hendrix 'Scuse me while I kill this fly Help Me! Help Me! post=0, limit=7, capacity=7: 'java.nio.HeapByteBuffer[pos=0 lim=7 cap=7]' post=0, limit=3, capacity=3: 'Hi!'