ByteBuffer bb = ByteBuffer.allocate(BSIZE);
bb.asCharBuffer().put("Howdy!");
char c;
while((c = bb.getChar()) != 0)
System.out.print(c + " ");
bb.rewind();
// Store and read a short:
bb.asShortBuffer().put((short)471142);
System.out.println(bb.getShort());
bb.rewind();
// Store and read an int:
bb.asIntBuffer().put(99471142);
System.out.println(bb.getShort());
bb.rewind();
为什么bb.getChar()一次只能获得一个英文字母
而bb.getShort(),bb.getShort()一次就能获得放入的数字
而API中他们的定义都是:
读取此缓冲区的当前位置之后的两个字节,根据当前的字节顺序将它们组成 short(或char或int) 值,然后将该位置增加 2
怎么结果不是类似的
还有,ByteBuffer是抽象类,它的get,put方法都是抽象的,怎么可以返回值?
bb.asCharBuffer().put("Howdy!");
char c;
while((c = bb.getChar()) != 0)
System.out.print(c + " ");
bb.rewind();
// Store and read a short:
bb.asShortBuffer().put((short)471142);
System.out.println(bb.getShort());
bb.rewind();
// Store and read an int:
bb.asIntBuffer().put(99471142);
System.out.println(bb.getShort());
bb.rewind();
为什么bb.getChar()一次只能获得一个英文字母
而bb.getShort(),bb.getShort()一次就能获得放入的数字
而API中他们的定义都是:
读取此缓冲区的当前位置之后的两个字节,根据当前的字节顺序将它们组成 short(或char或int) 值,然后将该位置增加 2
怎么结果不是类似的
还有,ByteBuffer是抽象类,它的get,put方法都是抽象的,怎么可以返回值?
if (bigEndian)
putCharB(bb, bi, x);
else
putCharL(bb, bi, x);
}static void putCharB(ByteBuffer bb, int bi, char x) {
bb._put(bi + 0, char1(x));
bb._put(bi + 1, char0(x));
}static void putCharL(ByteBuffer bb, int bi, char x) {
bb._put(bi + 0, char0(x));
bb._put(bi + 1, char1(x));
}private static byte char1(char x) { return (byte)(x >> 8); }
private static byte char0(char x) { return (byte)(x >> 0); }从上面的源代码可以看出,它每次存放的都是两个字节,不管其是英文字符还是其他的字符。另:ByteBuffer 的实现类是 HeapByteBuffer,是一个无修饰关键字的类,不在 JDK API 帮助中存在。
bb.asShortBuffer().put((short)471142);
short c;
while((c = bb.getShort()) != 0)
System.out.print(c + " ");
这样的输出结果是
12390 111 119 100 121 33
我怎么看都没法在二进制数中找到关系
这是怎么得来的?
应该是内部的实现机制的问题,getchar应该是指读入一个字节,而getshort应该是读入一个字符串=======================================================================================
getChar 读取的是一个字符,而不是字节。
getShort 读取 short 类型的值,而不是字符串
并没有看见代码中哪里有交给HeapByteBuffer实现的代码
还有,说明一点
用eclipse打开源代码方便些