Java ByteArrayInputStream: 바이트 배열 읽기 실전 가이드
Java ByteArrayInputStream
이 문서는 Java의 ByteArrayInputStream을 사용하여 바이트 배열에서 데이터를 읽는 방법을 설명하며, 생성자, 핵심 메서드, 실전 예제를 다룹니다.
ByteArrayInputStream이란?
java.io 패키지의 ByteArrayInputStream 클래스는 InputStream을 구현하며 바이트 배열을 입력 스트림처럼 다룰 수 있게 합니다. 제공된 배열의 사본을 내부적으로 저장하여 랜덤 액세스와 효율적 읽기를 가능하게 합니다.
참고: 스트림은 외부 소스가 아닌 배열 자체에서 읽으므로 모든 연산은 메모리 기반입니다.
ByteArrayInputStream 생성하기
java.io.ByteArrayInputStream을 임포트하고 인스턴스화합니다. 전체 배열이나 일부분을 읽을 수 있습니다.
ByteArrayInputStream input = new ByteArrayInputStream(byte[] arr);
ByteArrayInputStream input = new ByteArrayInputStream(byte[] arr, int start, int length);
두 번째 생성자는 인덱스 start에서 length 바이트를 읽습니다.
핵심 메서드
read()
int read() - 다음 바이트를 읽거나 끝에 도달하면 -1을 반환합니다.
int read(byte[] b) - 제공된 배열을 데이터로 채웁니다.
int read(byte[] b, int off, int len) - off 오프셋부터 b에 최대 len 바이트를 읽습니다.
예제: 바이트 읽기
import java.io.ByteArrayInputStream;
public class Main {
public static void main(String[] args) {
byte[] array = {1, 2, 3, 4};
try (ByteArrayInputStream input = new ByteArrayInputStream(array)) {
System.out.print("Bytes read: ");
int value;
while ((value = input.read()) != -1) {
System.out.print(value + ", ");
}
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
}
}
실행 결과
Bytes read: 1, 2, 3, 4,
available()
블로킹 없이 여전히 읽을 수 있는 바이트 수를 반환합니다.
import java.io.ByteArrayInputStream;
public class Main {
public static void main(String[] args) {
byte[] array = {1, 2, 3, 4};
try (ByteArrayInputStream input = new ByteArrayInputStream(array)) {
System.out.println("Initially: " + input.available());
input.read();
input.read();
System.out.println("After 2 reads: " + input.available());
} catch (Exception e) {
e.printStackTrace();
}
}
}
실행 결과
Initially: 4
After 2 reads: 2
skip()
요청된 바이트 수만큼 스트림 위치를 전진시킵니다.
import java.io.ByteArrayInputStream;
public class Main {
public static void main(String[] args) {
byte[] array = {1, 2, 3, 4};
try (ByteArrayInputStream input = new ByteArrayInputStream(array)) {
input.skip(2);
System.out.print("After skip: ");
int value;
while ((value = input.read()) != -1) {
System.out.print(value + ", ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
실행 결과
After skip: 3, 4,
close()
ByteArrayInputStream을 닫는 것은 no-op(아무 동작도 하지 않음)입니다. 닫은 후에도 스트림을 계속 사용할 수 있습니다. 이 메서드는 API 호환성을 위해 존재합니다.
기타 유용한 메서드
| 메서드 | 설명 |
mark(int readlimit) | 현재 위치를 표시합니다. |
reset() | 마지막 표시 위치로 돌아갑니다. |
markSupported() | 항상 true를 반환합니다. |
finalize() | 리소스 해제를 보장합니다(이 클래스에서는 효과 없음). |
전체 API는 공식 Java 문서를 참조하세요.