Java FileInputStream 완전 정복: 핵심 메서드와 실전 코드 예제
Java FileInputStream 클래스
이 튜토리얼은 Java의 FileInputStream을 다루며, 핵심 메서드, 실용적 사용법, 실전 예제를 안내합니다.
java.io 패키지의 FileInputStream 클래스는 파일에서 원시 바이트 데이터를 읽을 수 있게 합니다. 추상 InputStream 클래스를 확장하여 파일 I/O에 대한 구체적인 구현을 제공합니다.
FileInputStream 생성하기
클래스를 임포트하고 파일 경로나 File 객체로 인스턴스화합니다.
1. 파일 경로 사용
FileInputStream input = new FileInputStream("path/to/file.txt");
지정된 경로의 파일과 연결된 스트림을 엽니다.
2. File 객체 사용
File file = new File("file.txt");
FileInputStream input = new FileInputStream(file);
FileInputStream의 주요 메서드
이 클래스는 InputStream의 모든 추상 메서드를 구현하고 몇 가지 고유 메서드를 추가합니다. 가장 자주 사용되는 것들은 다음과 같습니다.
read()
int read() - 단일 바이트를 읽어 int로 반환(EOF 시 -1).
int read(byte[] b) - 제공된 배열을 바이트로 채웁니다.
int read(byte[] b, int off, int len) - off 오프셋부터 b에 최대 len 바이트를 읽습니다.
예제: 텍스트 파일을 바이트 단위로 읽기.
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) {
try (FileInputStream input = new FileInputStream("input.txt")) {
System.out.println("Data in the file:");
int byteRead;
while ((byteRead = input.read()) != -1) {
System.out.print((char) byteRead);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
실행 결과
Data in the file: This is a line of text inside the file.
available()
블로킹 없이 읽을 수 있는 바이트 수를 반환합니다.
try (FileInputStream input = new FileInputStream("input.txt")) {
System.out.println("Available at start: " + input.available());
input.read();
input.read();
input.read();
System.out.println("Available after 3 reads: " + input.available());
}
실행 결과
Available at start: 39
Available after 3 reads: 36
skip()
지정된 바이트 수만큼 스트림을 전진시키며 건너뜁니다.
try (FileInputStream input = new FileInputStream("input.txt")) {
input.skip(5); // "This " 건너뛰기
int byteRead;
while ((byteRead = input.read()) != -1) {
System.out.print((char) byteRead);
}
}
실행 결과
is a line of text inside the file.
close()
스트림을 닫고 시스템 자원을 해제합니다. 위 예제처럼 try-with-resources 블록을 사용하면 close()가 자동으로 호출됩니다.
추가 FileInputStream 메서드
| 메서드 | 설명 |
finalize() | 가비지 컬렉션 전 close() 호출을 보장합니다. |
getChannel() | 스트림과 연결된 FileChannel을 반환합니다. |
getFD() | 기본 파일 디스크립터를 제공합니다. |
mark(int readlimit) | 나중 재설정을 위해 현재 위치를 표시합니다. |
reset() | 스트림을 마지막 표시 위치로 재설정합니다. |
더 깊은 통찰을 위해 공식 Java 문서를 참조하세요: Java FileInputStream (공식 Java 문서).