Я пытался понять, как работает Java ByteBuffer. Моя цель - написать строку до ByteBuffer и прочитать его обратно. Я хочу понять, как ByteBuffer
свойства, подобные Limit, Capacity, Remaining, Position
, пострадают из-за операций чтения/записи.Понимание java 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());
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()
и никаких изменений в стоимости, если различные поля после записи и чтения операций.
Update
Ниже рабочая часть кода из 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 [])'. Вы не можете получить все байты, о которых вы просите. Указанный буфер байтового массива не может быть полностью заполнен (так как вы можете достичь конца потока до этого, или поток может иметь другие причины, чтобы дать частичное сообщение в ответ). –