파일 채널

파일 채널 (FileChannel)

파일에 대한 읽기·쓰기·잠금·매핑을 수행하는 채널이에요. 파일을 다루는 가장 강력한 채널 타입입니다.

출처: Java API Reference

본문

FileChannel은 파일에 대한 읽기, 쓰기, 크기 조정, 잠금, 메모리 매핑을 수행하는 채널이에요.

public abstract class FileChannel extends AbstractInterruptibleChannel
implements SeekableByteChannel, GatheringByteChannel, ScatteringByteChannel

파일 채널은 FileInputStream·FileOutputStream·RandomAccessFilegetChannel() 메서드로 얻을 수 있어요.

주요 메서드:

public abstract int read(ByteBuffer dst) throws IOException
public abstract int write(ByteBuffer src) throws IOException
public abstract long position() throws IOException
public abstract FileChannel position(long newPosition) throws IOException
public abstract long size() throws IOException
public abstract FileChannel truncate(long size) throws IOException
public abstract void force(boolean metaData) throws IOException
public abstract MappedByteBuffer map(FileChannel.MapMode mode, long position, long size) throws IOException
public abstract FileLock lock(long position, long size, boolean shared) throws IOException
public abstract FileLock tryLock(long position, long size, boolean shared) throws IOException
public abstract void transferTo(long position, long count, WritableByteChannel target) throws IOException
  • map() — 파일 영역을 메모리에 매핑해 MappedByteBuffer로 다뤄요.
  • lock()/tryLock() — 파일 영역을 잠가 동시 접근을 제어해요.
  • transferTo()/transferFrom() — 채널 간 데이터를 효율적으로 전송해요.
  • force() — 버퍼된 변경을 디스크에 강제 반영합니다.

파일 채널은 스레드 안전하며, 위치 독립적인 연산(메서드에 명시적 위치를 받는 read/write)과 위치 의존 연산을 모두 지원해요. FileChannel.MapMode는 매핑 모드를 나타냅니다.

더 알아보기 (Learn more)