- Writing data to the buffer [write mode, create a bytebuffer, clear(), compact()]
channel.read(buffer)
2. The put method of the buffer
buffer.put(byte) buffer.put((byte)'a')..
buffer.put(byte[])
- Reading data from the buffer
1. The write method of the channel
2. The get method of the buffer // Each call to the get method will affect the position.
3. The rewind method (accordion), can reset the position to 0, used for repeating data.
4. The mark&reset method, mark the position with the mark method, and jump back to the mark with the reset method to re-execute.
5. The get(i) method, get the data at a specific position, but does not affect the position.
- String operations
- Storing strings in a buffer
ByteBuffer buffer = ByteBuffer.allocate(10);
buffer.put("sunshuai".getBytes());
buffer.flip();
while (buffer.hasRemaining()) {
System.out.println("buffer.get() = " + (char)buffer.get());
}
buffer.clear();
ByteBuffer buffer = Charset.forName("UTF-8").encode("sunshuai");
1. The encode method automatically encodes the string according to the character set and stores it in the ByteBuffer.
2. Automatically sets the ByteBuffer to read mode and cannot manually call the flip method.
ByteBuffer buffer = StandardCharsets.UTF_8.encode("sunshuai");
while (buffer.hasRemaining()) {
System.out.println("buffer.get() = " + (char) buffer.get());
}
buffer.clear();
1. The encode method automatically encodes the string according to the character set and stores it in the ByteBuffer.
2. Automatically sets the ByteBuffer to read mode and cannot manually call the flip method.
ByteBuffer buffer = ByteBuffer.wrap("sunshuai".getBytes());
while (buffer.hasRemaining()) {
System.out.println("buffer.get() = " + (char) buffer.get());
}
buffer.clear();
- Converting data in the buffer to a string
ByteBuffer buffer = ByteBuffer.allocate(10);
buffer.put("孙".getBytes());
buffer.flip();
CharBuffer result = StandardCharsets.UTF_8.decode(buffer);
System.out.println("result.toString() = " + result.toString());