정리/Java
Java IO RandomAccessFile 만으로 파일 읽기
워로디스
2026. 2. 4. 22:14
아래는 Java의 RandomAccessFile 클래스를 사용하여 파일의 특정 offset부터 length만큼 byte[]로 읽는 예제 코드입니다.
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class FileReadExample {
public static byte[] readBytesFromFile(File file, long offset, int length) throws IOException {
try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
// 파일 크기 확인
long fileLength = raf.length();
if (offset < 0 || offset >= fileLength) {
throw new IllegalArgumentException("Offset is out of file bounds.");
}
// 읽을 수 있는 최대 바이트 수 계산
int bytesToRead = (int) Math.min(length, fileLength - offset);
byte[] buffer = new byte[bytesToRead];
// 위치 이동 후 읽기
raf.seek(offset);
raf.readFully(buffer); // 또는 raf.read(buffer, 0, bytesToRead);
return buffer;
}
}
public static void main(String[] args) throws IOException {
File file = new File("example.dat");
long offset = 1024;
int length = 512;
byte[] data = readBytesFromFile(file, offset, length);
System.out.println("Read " + data.length + " bytes from file.");
}
}
요점
raf.seek(offset)으로 읽기 시작 위치 지정raf.readFully(buffer)는 버퍼가 가득 찰 때까지 읽음 (EOF 예외 주의)length가 파일 끝을 초과하지 않도록 검사
필요에 따라 readFully() 대신 read()를 써서 EOF까지 읽히는 양에 따라 다르게 처리할 수도 있습니다.