今天使用JDK1.8中的ByteBuffer 发现其中基本数据必须要是偶数个的

private static void symmertricScramble(CharBuffer cb) {
while (cb.hasRemaining()) {
cb.mark();
char c1 = cb.get();
char c2 = cb.get();
cb.reset();
cb.put(c2).put(c1);
}
}

public static void main(String[] args) throws Exception {
//如果这里是奇数个的数据就会抛出BufferUnderflowException
char[] chars = "UsingCharBuffer2".toCharArray();
ByteBuffer bb = ByteBuffer.allocate(chars.length * 2);
CharBuffer cb = bb.asCharBuffer();


cb.put(chars);
// System.out.println("pos:" + cb.position() + " limit:" + cb.limit() + " cap:" + cb.capacity() + " mark:" + cb.mark());
cb.flip();

symmertricScramble(cb);
System.out.println(cb.rewind());
}

posted @ 2016-07-25 15:23  巡音  阅读(287)  评论(0编辑  收藏  举报