Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java RandomAccessFile로 .txt 파일 읽는 방법 (readLine 활용 예제)

파일 입출력의 기본 원리

일반적인 파일 입출력에서는 데이터를 파일의 시작 지점부터 순차적으로만 읽거나 쓸 수 있으며, 임의의 위치에 곧바로 접근하는 것은 불가능합니다.

하지만 Java의 java.io.RandomAccessFile 클래스를 사용하면 파일 내 어느 위치든 자유롭게 이동하면서 데이터를 읽고 쓸 수 있습니다.

파일 포인터(File Pointer)란?

RandomAccessFile은 마치 대용량 바이트 배열처럼 동작하며, 현재 위치를 가리키는 인덱스 역할의 파일 포인터를 내부적으로 관리합니다. 이 포인터의 위치는 getFilePointer() 메서드로 확인할 수 있고, seek() 메서드를 사용해 원하는 위치로 자유롭게 이동시킬 수 있습니다.

이 클래스는 파일에 데이터를 읽고 쓰기 위한 다양한 메서드를 제공합니다. 그중 readLine() 메서드는 파일에서 다음 한 줄을 읽어 String 형태로 반환합니다.

RandomAccessFile로 파일 읽는 단계

readLine() 메서드를 사용해 파일에서 데이터를 읽으려면 아래 단계를 따릅니다.

  • 읽고자 하는 파일의 경로를 문자열로 전달하여 File 객체를 생성합니다.

  • StringBuffer 객체를 생성합니다.

  • 앞서 만든 File 객체와 접근 모드 문자열(r: 읽기, rw: 읽기/쓰기 등)을 함께 전달하여 RandomAccessFile 객체를 생성합니다.

  • 파일 포인터의 위치가 파일 길이(length() 메서드)보다 작은 동안 반복문을 실행합니다.

  • 읽어온 각 줄을 StringBuffer 객체에 추가(append)합니다.

예제 코드

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
    public static void main(String args[]) throws IOException {
        String filePath = "D://input.txt";
        // File 클래스 인스턴스 생성
        File file = new File(filePath);
        // StringBuffer 인스턴스 생성
        StringBuffer buffer = new StringBuffer();
        // RandomAccessFile 인스턴스 생성
        RandomAccessFile raFile = new RandomAccessFile(file, "rw");
        // readLine() 메서드로 한 줄씩 읽기
        while(raFile.getFilePointer() < raFile.length()) {
            buffer.append(raFile.readLine()+System.lineSeparator());
        }
        String contents = buffer.toString();
        System.out.println("Contents of the file: \n"+contents);
    }
}

실행 결과

Contents of the file:
Tutorials Point originated from the idea that there exists a class of readers who respond better 
to online content and prefer to learn new skills.
Our content and resources are freely available and we prefer to keep it that way to encourage 
our readers acquire as many skills as they would like to.
We don’t force our readers to sign up with us or submit their details either.
Enjoy the free content

실무 활용 시 주의사항

실제 프로젝트에서는 파일 리소스 누수를 방지하기 위해 try-with-resources 구문을 사용해 RandomAccessFile을 자동으로 닫아주는 것이 좋습니다. 또한 readLine() 메서드는 UTF-8과 같은 멀티바이트 문자 인코딩을 올바르게 처리하지 못할 수 있으므로, 한글이 포함된 파일을 다룰 때는 FileReader나 Files.readAllLines() 같은 대안도 함께 고려하는 것이 안전합니다.