Java Files.newByteChannel
Read a byte at a chosen position through a seekable channel.
A simple example
Files.newByteChannel
- Start with Three bytes, 4, 7, 9
- Do this Read at byte offset 1
- Result 7
Syntax
public static SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException
JDK 21 declarations (2)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaRead the third parcel status without scanning earlier records
A parcel kiosk stores one byte per locker, ordered by locker number. A technician wants the third locker's status and can jump directly to that byte because all records have the same width.
import java.nio.file.*;
import java.nio.ByteBuffer;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path board = Files.write(desk.resolve("lockers.bin"), new byte[]{6, 8, 9});
try (var channel = Files.newByteChannel(board)) {
channel.position(2);
ByteBuffer one = ByteBuffer.allocate(1);
if (channel.read(one) == 1) System.out.println(one.get(0));
}
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
9
Locker three begins at byte offset two because positions start at zero.
Update one seat in a fixed-width chart
A ticket desk stores a short row as a sequence of seat-status bytes. Change only the middle seat in place and verify that the neighboring seat markers survive the update.
import java.nio.file.*;
import java.nio.ByteBuffer;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path row = Files.writeString(desk.resolve("seats.txt"), "AAA");
try (var channel = Files.newByteChannel(row, StandardOpenOption.WRITE)) {
channel.position(1);
ByteBuffer marker = ByteBuffer.wrap(new byte[]{'B'});
while (marker.hasRemaining()) channel.write(marker);
}
System.out.println(Files.readString(row));
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
ABA
Writing at position one changes the second byte without truncating the row.
Read a display preset
A museum sign saves three brightness levels as individual bytes. Read the unsigned byte at the indicated zero-based offset. Which stored sample is returned?
What to watch for
Offsets count bytes. An offset in the middle of a multibyte text character is unsuitable for decoding that character independently.