FileChannel Read Into ByteBuffer

Read a file in fixed-size chunks with FileChannel.read, flipping the ByteBuffer between write and read modes instead of loading the whole file.

JavaData Integrity

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 ChunkedFileReader {

    public static void main(String[] args) throws IOException {
        Path log = Files.createTempFile("events-", ".log");
        Files.writeString(log, "start\nmiddle\nend\n", StandardCharsets.UTF_8);

        try (FileChannel channel = FileChannel.open(log, StandardOpenOption.READ)) {
            ByteBuffer buffer = ByteBuffer.allocate(8);
            while (channel.read(buffer) != -1) { // 写模式:通道读入 buffer
                buffer.flip(); // 切换到读模式
                System.out.print(StandardCharsets.UTF_8.decode(buffer));
                buffer.clear(); // 复位回写模式继续读
            }
        }
        Files.deleteIfExists(log);
    }
}

What the code does

FileChannel Read Into ByteBuffer comes down to the class ChunkedFileReader.

Repetition is confined to while (channel.read(buffer) != -1) { // 写模式:通道读入 buffer — the rest of the file is straight-line. No finally block here — resources declared in the try header close themselves in reverse order.

Statements that matter

Files.writeString(log, "start\nmiddle\nend\n", StandardCharsets.UTF_8);
Path log = Files.createTempFile("events-", ".log");
ByteBuffer buffer = ByteBuffer.allocate(8);

Interactive Tools for This Topic

FAQ

How do you run FileChannel Read Into ByteBuffer?
The runtime alone is enough: execute the file as a complete program.