【发布时间】:2015-07-31 14:45:20
【问题描述】:
我一直在尝试了解 Java ByteBuffer 的工作原理。我的目标是将 string 写入 ByteBuffer 并将其读回。我想了解像Limit, Capacity, Remaining, Position 这样的ByteBuffer 属性如何因读/写操作而受到影响。
以下是我的测试程序(为简洁起见,删除了 import 语句)。
public class TestBuffer {
private ByteBuffer bytes;
private String testStr = "Stackoverflow is a great place to discuss tech stuff!";
public TestBuffer() {
bytes = ByteBuffer.allocate(1000);
System.out.println("init: " + printBuffer());
}
public static void main(String a[]) {
TestBuffer buf = new TestBuffer();
try {
buf.writeBuffer();
} catch (IOException e) {
e.printStackTrace();
}
buf.readBuffer();
}
// write testStr to buffer
private void writeBuffer() throws IOException {
byte[] b = testStr.getBytes();
BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(b));
in.read(bytes.array());
in.close();
System.out.println("write: " + printBuffer());
}
// read buffer data back to byte array and print
private void readBuffer() {
bytes.flip();
byte[] b = new byte[bytes.position()];
bytes.position(0);
bytes.get(b);
System.out.println("data read: " + new String(b));
System.out.println("read: " + printBuffer());
}
public String printBuffer() {
return "ByteBuffer [limit=" + bytes.limit() + ", capacity=" + bytes.capacity() + ", position="
+ bytes.position() + ", remaining=" + bytes.remaining() + "]";
}
}
输出
init: ByteBuffer [limit=1000, capacity=1000, position=0, remaining=1000]
write: ByteBuffer [limit=1000, capacity=1000, position=0, remaining=1000]
data read:
read: ByteBuffer [limit=0, capacity=1000, position=0, remaining=0]
如您所见,调用readBuffer() 后没有数据,写入和读取操作后各个字段的值也没有变化。
更新
下面是我最初试图理解的来自Android Screen Library 的工作代码
// retrieve the screenshot
// (this method - via ByteBuffer - seems to be the fastest)
ByteBuffer bytes = ByteBuffer.allocate (ss.width * ss.height * ss.bpp / 8);
is = new BufferedInputStream(is); // buffering is very important apparently
is.read(bytes.array()); // reading all at once for speed
bytes.position(0); // reset position to the beginning of ByteBuffer
请帮助我理解这一点。
谢谢
【问题讨论】:
-
你永远不应该忽略
in.read(byte[])的返回值。您可能无法检索到您要求的所有字节。给定的字节数组缓冲区可能未完全填充(因为您可能在此之前到达流的末尾,或者流可能有其他原因给出部分消息作为响应)。
标签: java bytebuffer