고급 JAVA/IO

ByteArrayIO 기초예제

행복하게사는게꿈 2020. 4. 12. 19:12
byte[] inSrc = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

byte[] outSrc = null;

ByteArrayInputStream input = null; // 스트림 선언

input = new ByteArrayInputStream(inSrc); //  객체 생성

ByteArrayOutputStream output = new ByteArrayOutputStream();

int data; // 읽어온 자료를 저장할 변수

// read() => byte 단위로 자료를 읽어와 int형으로 반환한다.

    -> 더이상 읽어올 자료가 없으면 -1를 반환한다.
    
while((data = input.read()) != -1){
	output.write(data); // 출력하기
}

outSrc = output.toByteArray(); // 출력된 스트림 값들을 배열로 변환해서 반환하는 메서드

// 파일 객체는 사용후 try-catch문으로 닫아준다.

try{
	input.close();
    output.close();
}catch(IOException e){
	e.printStackTrace();
}