FileChannel Truncate Shrinks Files

Truncate a file in place with FileChannel.truncate, which only takes effect below the current size and is a documented no-op at or above it.

JavaResilience

Code

snippet
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);
    }
}

How the snippet works

Everything happens inside the class LogShrinker.

Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

What to watch for

  • The imports (if any) point only at standard-library modules.

Applying it

Look for the size before:, size after 10:, size after 10 again: prefixes when the file runs; they tie each line to its step.

The statements worth quoting

channel.write(ByteBuffer.wrap("0123456789ABCDEFGHIJ".getBytes(StandardCharsets.UTF_8)));
Path log = Files.createTempFile("app-", ".log");
Files.deleteIfExists(log);

Interactive Tools for This Topic

FAQ

What does FileChannel Truncate Shrinks Files print when run?
No setup needed: run the file and look for labeled lines like `size before:`, `size after 10:`, `size after 10 again:` in the output.