实现说明
整个示例围绕类 LogShrinker组织。
try-with-resources 保证即使方法体抛出,声明的资源也会被关闭。
使用要点
- 跑完文件,输出里会留下标记——
size before:、size after 10:、size after 10 again:。
常见问题
运行「FileChannel.truncate 原地收缩文件」会打印什么?
运行文件本身,size before:、size after 10:、size after 10 again: 这些前缀各对应一段演示逻辑。
核心语句
channel.write(ByteBuffer.wrap("0123456789ABCDEFGHIJ".getBytes(StandardCharsets.UTF_8)));
Path log = Files.createTempFile("app-", ".log");
Files.deleteIfExists(log);
代码示例
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class LogShrinker {
public static void main(String[] args) throws IOException {
Path log = Files.createTempFile("app-", ".log");
try (FileChannel channel = FileChannel.open(log,
StandardOpenOption.READ, StandardOpenOption.WRITE)) {
channel.write(ByteBuffer.wrap("0123456789ABCDEFGHIJ".getBytes(StandardCharsets.UTF_8)));
System.out.println("size before: " + Files.size(log));
// truncate 只在目标更小时 shrink 文件;目标 >= 当前大小是 no-op
channel.truncate(10);
System.out.println("size after 10: " + Files.size(log));
channel.truncate(10);
System.out.println("size after 10 again: " + Files.size(log));
}
System.out.println("content: [" + Files.readString(log) + "]");
Files.deleteIfExists(log);
}
}