Java FileReader 완전 정복: 종합 가이드와 실전 예제
Java FileReader 클래스
이 가이드는 Java의 FileReader를 다루며, 생성자, 핵심 메서드, 실전 예제를 안내합니다.
java.io 패키지의 FileReader 클래스는 파일에서 문자 데이터를 읽습니다. InputStreamReader를 확장하며 다양한 문자 인코딩을 지원합니다.
FileReader에 뛰어들기 전에 Java의 File API를 이해하고 있는지 확인하세요.
FileReader 생성하기
먼저 클래스를 임포트합니다:
import java.io.FileReader;
1. 파일명으로
FileReader input = new FileReader("path/to/file.txt");
지정된 파일을 여는 리더를 생성합니다.
2. File 객체로
File fileObj = new File("path/to/file.txt");
FileReader input = new FileReader(fileObj);
3. 캐릭터셋 지정 (Java 11+)
FileReader input = new FileReader("path/to/file.txt", StandardCharsets.UTF_8);
Charset을 사용하면 원하는 인코딩으로 파일을 읽을 수 있습니다.
FileReader의 핵심 메서드
FileReader는 Reader의 모든 메서드를 구현하고 자체 기능을 추가합니다.
read() 메서드
read() - 단일 문자를 읽습니다.
read(char[] array) - 배열을 문자로 채웁니다.
read(char[] array, int offset, int length) - offset부터 array에 length 문자를 읽습니다.
예제: "This is a line of text inside the file."을 포함하는 input.txt 읽기.
import java.io.FileReader;
class Main {
public static void main(String[] args) {
char[] buffer = new char[100];
try (FileReader reader = new FileReader("input.txt")) {
int readCount = reader.read(buffer);
System.out.println("Data in the file:");
System.out.println(new String(buffer, 0, readCount));
} catch (Exception e) {
e.printStackTrace();
}
}
}
실행 결과
Data in the file: This is a line of text inside the file.
참고: input.txt를 현재 작업 디렉토리에 두세요.
getEncoding() 메서드
리더가 사용하는 캐릭터셋을 조회합니다:
import java.io.FileReader;
import java.nio.charset.StandardCharsets;
class Main {
public static void main(String[] args) {
try {
FileReader defaultReader = new FileReader("input.txt");
FileReader utf8Reader = new FileReader("input.txt", StandardCharsets.UTF_8);
System.out.println("Default encoding: " + defaultReader.getEncoding());
System.out.println("UTF-8 encoding: " + utf8Reader.getEncoding());
} catch (Exception e) {
e.printStackTrace();
}
}
}
실행 결과
Default encoding: Cp1252
UTF-8 encoding: UTF-8
캐릭터셋이 지정되면 getEncoding()은 해당 캐릭터셋을 반환하고, 그렇지 않으면 플랫폼 기본값을 반영합니다.
close() 메서드
사용 후 항상 리더를 닫으세요. 위 try-with-resources 문이 자동으로 처리합니다.
추가 FileReader 메서드
| 메서드 | 설명 |
ready() | 스트림이 읽을 준비가 되었는지 나타냅니다. |
mark() | 스트림의 현재 위치를 표시합니다. |
reset() | 스트림을 가장 최근 표시 위치로 재설정합니다. |
더 자세한 내용은 공식 Java FileReader 문서를 참조하세요.