理解java ByteBuffer

时间:2015-07-31 14:45:21

标签: java bytebuffer

我一直在努力了解Java ByteBuffer的工作原理。我的目标是将字符串写入 ByteBuffer 并将其读回。我想了解ByteBuffer Limit, Capacity, Remaining, Position属性如何因读/写操作而受到影响。

以下是我的测试程序(为简洁起见,删除了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

请帮助我理解这一点。

由于

3 个答案:

答案 0 :(得分:3)

您的缓冲区永远不会被填充。 bytes.array()只是检索后备字节数组。如果你写任何东西,那么ByteBuffer字段 - 当然除了数组本身 - 不受影响。所以头寸保持为零。

您在in.read(bytes.array())中所做的与byte[] tmp = bytes.array()后跟in.read(tmp)相同。对tmp变量的更改无法反映在bytes实例中。更改后备阵列,这可能意味着ByteBuffer的内容也会更改。但是支持字节数组的偏移 - 包括位置限制 - 不是。

您应该只使用任何ByteBuffer方法(不带索引)填充put,例如put(byte[])

我将提供一个代码片段,可以让您思考如何处理字符串,编码以及字符和字节缓冲区:

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.StandardCharsets;

public class TestBuffer {

    private static final String testStr = "Stackoverflow is a great place to discuss tech stuff!";
    private static final boolean END_OF_INPUT = true;

    private ByteBuffer bytes = ByteBuffer.allocate(1000);

    public TestBuffer() {

        System.out.println("init   : " + bytes.toString());
    }

    public static void main(String a[]) {
        TestBuffer buf = new TestBuffer();
        buf.writeBuffer();
        buf.readBuffer();
    }

    // write testStr to buffer
    private void writeBuffer() {
        CharBuffer testBuffer = CharBuffer.wrap(testStr);
        CharsetEncoder utf8Encoder = StandardCharsets.UTF_8.newEncoder();
        CoderResult result = utf8Encoder.encode(testBuffer, bytes, END_OF_INPUT);
        if (result.isError()) {
            bytes.clear();
            throw new IllegalArgumentException("That didn't go right because " + result.toString());
        }
        if (result.isOverflow()) {
            bytes.clear();
            throw new IllegalArgumentException("Well, too little buffer space.");
        }
        System.out.println("written: " + bytes.toString());
        bytes.flip();
    }

    // read buffer data back to byte array and print
    private void readBuffer() {
        byte[] b = new byte[bytes.remaining()];
        bytes.get(b);
        System.out.println("data   : " + new String(b, StandardCharsets.UTF_8));
        System.out.println("read   : " + bytes.toString());
        bytes.clear();
    }
}

请注意,缓冲区和流实际上是处理顺序数据的两种不同方式。如果你试图同时使用它们,你可能会试图聪明。

您也可以在CharBufferByteBuffer使用byte[]缓冲区和StringReader包裹ReaderInputStream的情况下解决此问题。

Android代码完全滥用ByteBuffer。它应该只创建一个byte[]并将其包装起来,将限制设置为容量。无论您做什么, 都不要将其用作ByteBuffer处理 的示例。它使我的眼睛厌恶地流水。像这样的代码是一个等待发生的错误。

答案 1 :(得分:1)

您没有在writeBuffer()方法中写任何内容。

您可以使用类似bytes.put(b)的内容。

答案 2 :(得分:0)

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

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

1) writeBuffer()方法

如上文Maarten Bodewes关于字节缓冲区数组性质的解释,您不能直接使用byteBuffer.array()来读取

中的流

或者,如果您想继续测试 InputStream ByteBuffer 作为示例(这也是服务器端应用程序处理传入消息的一种常见做法) ,则需要一个附加的字节数组。

2)readBuffer()方法

原始代码的好处是使用一个额外的字节数组来检索字节缓冲区中的上下文以进行打印。

但是,这里的问题是flip()position()方法的不正确使用。

  1. 仅应在将字节缓冲区的状态flip()更改为storing context之前,调用exporting context方法。因此,此方法应该出现在bytes.get(b);行的前面。在提供的示例中,在行byte[] b = new byte[bytes.position()];之前调用此方法为时过早,因为flip()方法会将字节缓冲区的 position 标志更改为0,同时将< strong> limit 标志当前位置。

  2. 在示例代码中没有必要将字节缓冲区的位置显式设置为0。如果您希望以后再从当前位置开始将上下文再次存储到字节缓冲区中(即不覆盖其中的现有上下文),则应遵循以下工作流程:

    2.1存储字节缓冲区的当前位置: int pos = bytebuffer.position();
    2.2用字节缓冲区进行处理,这可能会影响其位置标志: bytebuffer.get(byte[] dst)等。
    2.3将字节缓冲区的位置标志恢复为原始值: bytebuffer.position(pos);


在这里,我略微修改了您的示例代码以实现您想要的操作:

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

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());
        byte[] dst = new byte[b.length];
        in.read(dst);
        bytes.put(dst);
        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);
        int pos = bytes.position();
        bytes.flip();   // bytes.rewind(); could achieve the same result here, use which one depends on whether:
                        // (1) reading to this bytebuffer is finished and fine to overwrite the current context in this bytebuffer afterwards: can use flip(); or 
                        // (2) just want to tentatively traverse this bytebuffer from the begining to current position, 
                        //      and keep writing to this bytebuffer again later from current position.      
        bytes.get(b);
        bytes.position(pos);
        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() + "]";
    }

}