java类库详细讲解
源代码在线查看: putbytes.html
Putting Bytes into a ByteBuffer
(Java Developers Almanac Example)
BODY CODE {font-family: Courier, Monospace; font-size: 11pt} TABLE, BODY {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt} PRE {font-family: Courier, Monospace; font-size: 10pt} H3 {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11pt} A.eglink {text-decoration: none} A:hover.eglink {text-decoration: underline} -->
The Java Developers Almanac 1.4
Order this book from Amazon.
Home
>
List of Packages
>
java.nio
[27 examples]
>
Byte Buffers
[8 examples]
e160.
Putting Bytes into a ByteBuffer
A ByteBuffer has a capacity which determines how many bytes it
contains. This capacity can never change. Any byte in the
ByteBuffer can be modified using the absolute version of put(),
which takes an index in the range [0..capacity-1].
The bytes in a ByteBuffer can also be set using the relative
version of put(), which uses the position and limit properties of
the buffer. In particular, this version of put() sets the byte at
the position and advances the position by one. put() cannot set
bytes past the limit (even though limit might be less than the
capacity). The position is always <= limit and limit is always <=
capacity.
// Create an empty ByteBuffer with a 10 byte capacity
ByteBuffer bbuf = ByteBuffer.allocate(10);
// Get the buffer's capacity
int capacity = bbuf.capacity(); // 10
// Use the absolute put().
// This method does not affect the position.
bbuf.put((byte)0xFF); // position=0
// Set the position
bbuf.position(5);
// Use the relative put()
bbuf.put((byte)0xFF);
// Get the new position
int pos = bbuf.position(); // 6
// Get remaining byte count
int rem = bbuf.remaining(); // 4
// Set the limit
bbuf.limit(7); // remaining=1
// This convenience method sets the position to 0
bbuf.rewind(); // remaining=7
Related Examples
e158.
Creating a ByteBuffer
e159.
Getting Bytes from a ByteBuffer
e161.
Converting Between a ByteBuffer an a Byte Array
e162.
Getting and Setting Non-Byte Java Types in a ByteBuffer
e163.
Creating a Non-Byte Java Type Buffer on a ByteBuffer
e164.
Using a ByteBuffer to Store Strings
e165.
Setting the Byte Ordering for a ByteBuffer
See also:
File Locking
Files
Sockets
Streams
© 2002 Addison-Wesley.