实现说明
整个示例围绕类 ChannelSeek组织。
资源写在 try 头部,关闭由编译器生成、异常安全。
使用要点
- 跑完文件,输出里会留下标记——
size =、at 6:、at 0:。
常见问题
运行「SeekableByteChannel 偏移读取与原地改写」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 size =、at 6:、at 0: 标签标明各步骤。
核心语句
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");
代码示例
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);
}
}