비동기 파일 채널

비동기 파일 채널 (AsynchronousFileChannel)

파일에 대한 비동기 I/O를 수행하는 채널이에요. 파일 읽기·쓰기·잠금을 비동기적으로 수행하고 완료 핸들러로 결과를 받습니다.

출처: Java API Reference

본문

AsynchronousFileChannel은 파일에 대한 비동기 I/O를 수행하는 채널이에요.

public abstract class AsynchronousFileChannel extends Object
implements AsynchronousChannel

파일 채널은 open() 정적 메서드로 열며, 파일 패스와 옵션을 지정합니다.

public static AsynchronousFileChannel open(Path file, Set<? extends OpenOption> options,
        ExecutorService executor, FileAttribute<?>... attrs) throws IOException

주요 연산:

<A> void read(ByteBuffer dst, long position, A attachment,
        CompletionHandler<Integer, ? super A> handler)
<A> void write(ByteBuffer src, long position, A attachment,
        CompletionHandler<Integer, ? super A> handler)
Future<Integer> read(ByteBuffer dst, long position)
Future<Integer> write(ByteBuffer src, long position)
<A> void lock(long position, long size, boolean shared, A attachment,
        CompletionHandler<FileLock, ? super A> handler)
Future<FileLock> lock(long position, long size, boolean shared)
  • read()/write()는 위치를 지정해 비동기적으로 읽고 써요.
  • lock()으로 파일의 일부 영역을 잠글 수 있고, tryLock()으로 비차단 잠금도 시도할 수 있어요.
  • size()로 파일 크기를, truncate()로 파일을 잘라낼 수 있습니다.

비동기 소켓 채널처럼 완료 핸들러 방식과 Future 방식을 모두 지원합니다.

더 알아보기 (Learn more)