PHpullh
학습 라이브러리/Java/비동기 파일 I/O (AsynchronousFileChannel)

JAVA · 파일/IO

비동기 파일 I/O (AsynchronousFileChannel)

AsynchronousFileChannel로 논블로킹 파일 I/O를 수행합니다.

파일/IO고급AsynchronousFileChannel비동기IONIOByteBuffer

핵심 설명

AsynchronousFileChannel로 논블로킹 파일 I/O를 수행합니다.

Java code

import java.nio.channels.*;
import java.nio.file.*;
import java.nio.ByteBuffer;
import java.util.concurrent.Future;

public class AsyncFileIO {
    public static void main(String[] args) throws Exception {
        Path file = Files.createTempFile("async", ".txt");

        // 비동기 쓰기
        try (var channel = AsynchronousFileChannel.open(file,
                StandardOpenOption.WRITE)) {

            byte[] data = "비동기 파일 I/O 테스트 데이터입니다.".getBytes();
            ByteBuffer buffer = ByteBuffer.wrap(data);

            // Future 기반
            Future<Integer> writeFuture = channel.write(buffer, 0);
            int bytesWritten = writeFuture.get(); // 완료 대기
            System.out.println("쓴 바이트: " + bytesWritten);
        }

        // 비동기 읽기 — CompletionHandler 콜백
        try (var channel = AsynchronousFileChannel.open(file,
                StandardOpenOption.READ)) {

            ByteBuffer buffer = ByteBuffer.allocate(1024);

            channel.read(buffer, 0, buffer,
                new CompletionHandler<Integer, ByteBuffer>() {
                    @Override
                    public void completed(Integer result, ByteBuffer buf) {
                        buf.flip();
                        byte[] bytes = new byte[buf.remaining()];
                        buf.get(bytes);
                        System.out.println("읽은 내용: " + new String(bytes));
                    }

                    @Override
                    public void failed(Throwable exc, ByteBuffer buf) {
                        System.err.println("읽기 실패: " + exc.getMessage());
                    }
                });

            Thread.sleep(500); // 콜백 대기
        }

        Files.deleteIfExists(file);
    }
}

학습 팁

비동기 파일 I/O는 대용량 파일이나 다수의 파일을 동시에 처리할 때 유리합니다. 작은 파일은 동기 Files API가 더 간단합니다.

주의할 점

ByteBufferflip()을 호출하지 않으면 읽기 모드로 전환되지 않아 빈 데이터를 읽습니다.

자주 묻는 질문

비동기 파일 I/O (AsynchronousFileChannel)란 무엇인가요?

AsynchronousFileChannel 로 논블로킹 파일 I/O를 수행합니다.

비동기 파일 I/O (AsynchronousFileChannel) 학습 시 주의할 점은 무엇인가요?

ByteBuffer 의 flip() 을 호출하지 않으면 읽기 모드로 전환되지 않아 빈 데이터를 읽습니다.