← 中文资源

简体中文版本

FileChannel.truncate 原地收缩文件

truncate 按给定大小原地收缩文件:目标小于当前大小才生效,大于等于时是文档明确的 no-op;日志轮转、占位回收不用重写整个文件。

阅读英文原文

实现说明

整个示例围绕类 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);
    }
}