package kr.or.didt.basic;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
public class ByteAttayIoTest01 {
public static void main(String[] args) {
byte[] inSrc = {0,1,2,3,4,5,6,7,8,9};
byte[] outSrc = null;
ByteArrayInputStream input = new ByteArrayInputStream(inSrc);
ByteArrayOutputStream output = new ByteArrayOutputStream();
int data; //읽어온 데이터가 저장될 변수
//read()메서드 ==> 더 이상 읽어올 데이터가 없으면 -1을 반환한다.
while((data = input.read()) != -1){//-1이 아니면 읽어온데이터이다
output.write(data); //읽어온 데이터를 그대로 출력한다.
}
// 출력된 스트림 값들을 배열로 변환해서 저장하기
outSrc = output.toByteArray();
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("inSrc => " + Arrays.toString(inSrc));
System.out.println("outSrc => " + Arrays.toString(outSrc));
}
}
package kr.or.didt.basic;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
public class ByteArrayIOTest02 {
public static void main(String[] args) {
byte[] inSrc = {0,1,2,3,4,5,6,7,8,9};
byte[] outSrc = null;
byte[] temp = new byte[4]; //4개짜리 배열 생성
ByteArrayInputStream input = new ByteArrayInputStream(inSrc);
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
//읽어올 데이터가 있는지 확인
while(input.available() > 0){
// input.read(temp);
// output.write(temp);
// 실제 읽어온 byte수를 반환한다.
int len = input.read(temp);
//temp배열의 내용중 에서 0번째부터 len갯수만큼 출력한다.
output.write(temp, 0, len);
System.out.println("반복문 안에서 temp = "
+ Arrays.toString(temp));
}
outSrc = output.toByteArray();
System.out.println("inSrc => " + Arrays.toString(inSrc));
System.out.println("outSrc => " + Arrays.toString(outSrc));
input.close();
output.close();
} catch (IOException e) {
// TODO: handle exception
}
}
}