[chapter 15. 입출력]
stream : 자바에서 입출력을 수행하려면, 어느 한 쪽에서 다른 쪽으로 데이터를 전달하려면, 두 대상을 연결하고 데이터를 전송할 수 있는 무언가가 필요함. 이게 stream
->데이터를 운반하는데 사용되는 연결통로
바이트기반 스트림 - InputStream, OutputStream
FileInputStream, FileOutputStream
abstract int read() / abstract void write(int b)
int read(byte[] b) / void write(byte[] b)
int read(byte[[ b, int off, int len) / void write(byte[]b, int off, int len)
보조스트림 : 실제 데이터를 주고받는 스트림이 아니기 때문에 데이터를 입출력할 수 있는 기능은 없지만,
스트림의 기능을 향상시키거나 새로운 기능을 추가할 수 있음
스트림을 먼저 생성한 다음에 보조스트림 생성
FilterInputStream - 필터를 이용한 입출력 처리
BufferedInputStream - 버퍼를 이용한 입출력 성능향상
DataInputStream - int, float와 같은 기본형 단위로 데이터 처리
문자기반 스트림 - Reader, Writer
java에서는 char 형이 2byte.
FileReader, FileWriter
CharArrayWriter, CharArrayReader
close() : 입력소스를 닫음으로써 사용하고 있던 자원 반환
flush() : 스트림의 버퍼에 있는 모든 내용을 출력소스에 씀
바이트기반 스트림 - ByteArrayInputStream, ByteArrayOutputStream
while( (data = input.read()) != -1) {
output.write(data);
}
data = input.read() : read()로 호출한 반환값을 변수 data에 저장.
data != -1 : data에 저장된 값이 -1이 아닌지 비교.
available() : blocking 없이 읽어 올 수 있는 바이트의 수
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];
ByteArrayInputStream input = null;
ByteArrayOutputStream output = null;
input = new ByteArrayInputStream(inSrc);
output = new ByteArrayOutputStream();
System.out.println("Input Source : " + Arrays.toString(inSrc));
try {
while (input.available() > 0) { //
input.read(temp);
output.write(temp);
outSrc = output.toByteArray();
printArrays(temp, outSrc);
}
} catch (IOException e) {
e.getMessage();
System.out.println(e);
}
}
static void printArrays(byte[] temp, byte[] outSrc) {
System.out.println("Temp : " + Arrays.toString(temp));
System.out.println("Output Source : " + Arrays.toString(outSrc));
}
결과:

temp에 남아있던 6,7까지 출력됨.
배열의 내용 전체 출력 ----> 읽어온 만큼(len)만 출력
int len = input.read(temp);
output.write(temp, 0, len);
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];
ByteArrayInputStream input = null;
ByteArrayOutputStream output = null;
input = new ByteArrayInputStream(inSrc);
output = new ByteArrayOutputStream();
System.out.println("Input Source : " + Arrays.toString(inSrc));
try {
while (input.available() > 0) { //
int len = input.read(temp);
output.write(temp, 0, len);
outSrc = output.toByteArray();
printArrays(temp, outSrc);
}
} catch (IOException e) {
e.getMessage();
System.out.println(e);
}
}
static void printArrays(byte[] temp, byte[] outSrc) {
System.out.println("Temp : " + Arrays.toString(temp));
System.out.println("Output Source : " + Arrays.toString(outSrc));
}
결과 :
