了解java ByteBuffer

问题描述 投票:1回答:3

我一直试图了解Java ByteBuffer的工作方式。我的目的是将string写入ByteBuffer并读回。我想了解ByteBuffer之类的Limit, Capacity, Remaining, Position属性如何由于读/写操作而受到影响。

下面是我的测试程序(为简洁起见删除了导入语句。

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

请帮助我理解这一点。

谢谢


我一直试图了解Java ByteBuffer的工作方式。我的目的是将一个字符串写入ByteBuffer并读回。我想了解ByteBuffer属性如何,例如限制,容量,剩余量,...

java bytebuffer
3个回答
3
投票

您的缓冲区永远不会装满。 bytes.array()简单地检索后备字节数组。如果对此写入任何内容,则ByteBuffer字段(当然不包括数组本身)不受影响。因此位置保持在零。


1
投票
您未在ByteBuffer方法中编写任何内容。

您可以使用byte[]之类的东西。


0
投票
尽管很久以前已经回答了这个问题,但让我也补充一些信息。这里。

ByteBufferwriteBuffer()方法中分别存在两个问题,导致您无法获得预期的结果。

1)

bytes.put(b)方法

© www.soinside.com 2019 - 2024. All rights reserved.