GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||
GeezerVison is showing zetcode.com — Java ByteBuffer - working with byte buffers in Java Java ByteBufferLast modified: July 16, 2026
This Java ByteBuffer tutorial shows how to use the
Typical use cases include reading and writing files with
ByteBuffer
ByteBuffer is a class in the
The relationship between these properties is always:
Creating buffers
// Heap buffer
ByteBuffer buf = ByteBuffer.allocate(1024);
// Direct buffer (off-heap)
ByteBuffer bufDirect = ByteBuffer.allocateDirect(1024);
// Wrap existing array
byte[] data = {1, 2, 3, 4, 5};
ByteBuffer bufWrapped = ByteBuffer.wrap(data);
Writing and reading bytes
Data is written to a buffer with Main.java
import java.nio.ByteBuffer;
void main() {
ByteBuffer buf = ByteBuffer.allocate(10);
buf.put((byte) 10);
buf.put((byte) 20);
buf.put((byte) 30);
buf.flip();
while (buf.hasRemaining()) {
System.out.println(buf.get());
}
}
We allocate a 10-byte buffer, write three bytes, flip it, and read them back. buf.put((byte) 10); buf.put((byte) 20); buf.put((byte) 30); Three bytes are written to the buffer. After these writes, the position is 3 and the limit is 10 (the capacity). buf.flip();
while (buf.hasRemaining()) {
System.out.println(buf.get());
}
The $ java Main.java 10 20 30 Writing with absolute and relative positions
Both Main.java
import java.nio.ByteBuffer;
void main() {
ByteBuffer buf = ByteBuffer.allocate(8);
// Relative puts
buf.put((byte) 1);
buf.put((byte) 2);
// Absolute put at index 7
buf.put(7, (byte) 99);
buf.flip();
while (buf.hasRemaining()) {
System.out.println(buf.get());
}
}
The relative $ java Main.java 1 2 0 0 0 0 0 99 Bulk put and get
A Main.java
import java.nio.ByteBuffer;
import java.util.Arrays;
void main() {
byte[] input = {10, 20, 30, 40, 50};
ByteBuffer buf = ByteBuffer.allocate(16);
buf.put(input);
buf.flip();
byte[] output = new byte[buf.remaining()];
buf.get(output);
System.out.println(Arrays.toString(output));
}
The bulk $ java Main.java [10, 20, 30, 40, 50] Compact
The Main.java
import java.nio.ByteBuffer;
import java.util.Arrays;
void main() {
ByteBuffer buf = ByteBuffer.allocate(10);
buf.put(new byte[]{1, 2, 3, 4, 5, 6, 7, 8});
buf.flip();
// Read first three bytes
byte[] dst = new byte[3];
buf.get(dst);
System.out.println("Read: " + Arrays.toString(dst));
// Compact: move remaining bytes to front
buf.compact();
// Write more data
buf.put(new byte[]{9, 10});
buf.flip();
byte[] out = new byte[buf.remaining()];
buf.get(out);
System.out.println("Remaining: " + Arrays.toString(out));
}
After reading three bytes, five unread bytes remain. $ java Main.java Read: [1, 2, 3] Remaining: [4, 5, 6, 7, 8, 9, 10] Converting between strings and ByteBuffers
A Main.java
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
void main() {
String msg = "Hello, Java!";
// Encode string to ByteBuffer
ByteBuffer buf = StandardCharsets.UTF_8.encode(msg);
// Decode ByteBuffer to string
String decoded = StandardCharsets.UTF_8.decode(buf).toString();
System.out.println(decoded);
// Using wrap and Charset
byte[] data = msg.getBytes(StandardCharsets.UTF_8);
ByteBuffer buf2 = ByteBuffer.wrap(data);
String decoded2 = StandardCharsets.UTF_8.decode(buf2).toString();
System.out.println(decoded2);
}
$ java Main.java Hello, Java! Hello, Java! Byte order
The Main.java
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
void main() {
ByteBuffer buf = ByteBuffer.allocate(8);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putInt(0x12345678);
buf.flip();
System.out.printf("Big endian: 0x%08x%n", buf.getInt());
buf.clear();
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.putInt(0x12345678);
buf.flip();
System.out.printf("Little endian: 0x%08x%n", buf.getInt());
}
The same integer value is written and read using different byte orders. With big endian, the most significant byte is stored first; with little endian, the least significant byte is stored first. $ java Main.java Big endian: 0x12345678 Little endian: 0x78563412 View buffers
A Main.java
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
void main() {
ByteBuffer byteBuf = ByteBuffer.allocate(16);
byteBuf.putInt(100);
byteBuf.putInt(200);
byteBuf.putInt(300);
byteBuf.putInt(400);
byteBuf.flip();
IntBuffer intBuf = byteBuf.asIntBuffer();
while (intBuf.hasRemaining()) {
System.out.println(intBuf.get());
}
}
We write four integers into a IntBuffer intBuf = byteBuf.asIntBuffer();
The $ java Main.java 100 200 300 400 Reading a file with FileChannel
One of the most common uses of Main.java
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
void main() {
var path = Path.of("test.txt");
try (var channel = FileChannel.open(path, StandardOpenOption.READ)) {
ByteBuffer buf = ByteBuffer.allocate(1024);
int bytesRead = channel.read(buf);
if (bytesRead != -1) {
buf.flip();
var data = new byte[buf.remaining()];
buf.get(data);
System.out.println(new String(data));
}
}
}
We open a $ java Main.java Hello there!
For larger files, we would loop over Mark and reset
The buffer's position can be saved with Main.java
import java.nio.ByteBuffer;
void main() {
ByteBuffer buf = ByteBuffer.wrap(new byte[]{1, 2, 3, 4, 5});
System.out.println(buf.get()); // 1
System.out.println(buf.get()); // 2
buf.mark(); // mark at position 2
System.out.println(buf.get()); // 3
System.out.println(buf.get()); // 4
buf.reset(); // go back to position 2
System.out.println(buf.get()); // 3 again
}
After reading two bytes, we mark the position. After reading two more bytes, we reset to the mark, allowing us to re-read the data. $ java Main.java 1 2 3 4 3 Buffer rewind and clear
The Main.java
import java.nio.ByteBuffer;
void main() {
ByteBuffer buf = ByteBuffer.wrap(new byte[]{10, 20, 30});
System.out.println(buf.get()); // 10
System.out.println(buf.get()); // 20
buf.rewind();
System.out.println("After rewind:");
while (buf.hasRemaining()) {
System.out.println(buf.get());
}
buf.clear();
System.out.println("After clear, position: " + buf.position()
+ ", limit: " + buf.limit());
}
$ java Main.java 10 20 After rewind: 10 20 30 After clear, position: 0, limit: 3 SourceJava ByteBuffer - Language Reference
In this article, we have worked with Java AuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Java tutorials. | ||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |