Library contents

Java Files.newByteChannel

Read a byte at a chosen position through a seekable channel.

A simple example

Files.newByteChannel

  1. Start with Three bytes, 4, 7, 9
  2. Do this Read at byte offset 1
  3. Result 7
Offsets start at zero. Moving one byte past the start selects the second byte.

Syntax

Java 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.java

Read 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.

Result9
Main.java
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);
            }
        }
    }
}
Output
9

Locker three begins at byte offset two because positions start at zero.

Advertisements

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.

ResultABA
Main.java
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);
            }
        }
    }
}
Output
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?

Given12 · 80 · 200 | offset 2
Worked result200

What to watch for

Offsets count bytes. An offset in the middle of a multibyte text character is unsuitable for decoding that character independently.

Documentation for Files.newByteChannel