SeekableByteChannel Seeks And Patches
Seek a SeekableByteChannel to any byte offset, read or overwrite in place, and watch the same channel re-read after rewinding its position.
Code
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class ChannelSeek {
public static void main(String[] args) throws IOException {
Path log = Files.createTempFile("seek-", ".log");
Files.writeString(log, "alpha|bravo|charlie|delta\n", StandardCharsets.UTF_8);
try (SeekableByteChannel ch = Files.newByteChannel(log, StandardOpenOption.READ)) {
System.out.println("size = " + ch.size());
// 顺序读之外,通道还能直接跳到第 6 字节('b')按需读取
ch.position(6);
ByteBuffer buf = ByteBuffer.allocate(5);
ch.read(buf);
System.out.println("at 6: " + new String(buf.array(), StandardCharsets.UTF_8));
// position 往回拨:同一通道重读开头
ch.position(0);
buf.clear();
ch.read(buf);
System.out.println("at 0: " + new String(buf.array(), StandardCharsets.UTF_8));
}
// WRITE 通道按 position 原地改写:第 6 字节起的 5 个字节变成 BRAVO
try (SeekableByteChannel patch = Files.newByteChannel(log, StandardOpenOption.WRITE)) {
patch.position(6);
patch.write(ByteBuffer.wrap("BRAVO".getBytes(StandardCharsets.UTF_8)));
}
System.out.println("patched: " + Files.readString(log, StandardCharsets.UTF_8).strip());
Files.deleteIfExists(log);
}
}How it works
Structurally, expect the class ChannelSeek and nothing else.
try-with-resources closes each declared resource automatically on every exit path.
Points of care
- The language toolchain itself is the only prerequisite.
Applying it
Look for the size =, at 6:, at 0: prefixes as the file executes; they connect every printed line to the step behind it.
Statements that matter most here
Files.writeString(log, "alpha|bravo|charlie|delta\n", StandardCharsets.UTF_8);
patch.write(ByteBuffer.wrap("BRAVO".getBytes(StandardCharsets.UTF_8)));
Path log = Files.createTempFile("seek-", ".log");
FAQ
- What does SeekableByteChannel Seeks And Patches print when run?
- The script runs standalone; its 4 labeled outputs include `size =`, `at 6:`, `at 0:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.