Language/Java

[자바_API] 입출력 I/O

simDev1234 2022. 4. 5. 01:02

1. 스트림이란? 데이터를 운반하는데 사용되는 연결통로

  [생각] BJ는 온라인방송을 할 때, 왜 "스트리밍 중"이라고 할까?

 

2. 바이트기반 스트림_InputStream/OutPutStream 추상클래스 상속

입력스트림 출력스트림 입출력 대상의 종류
FileInputStream FileOutputStream 파일
ByteArrayInputStream ByteArrayOutputStream 메모리(byte배열)
PipedInputStream PipedOutputStream 프로세스(프로세스간의 통신)
AudioInputStream AudioOutputStream 오디오장치
.... .... ....

(1) InputStream 메서드

리턴타입 메소드  
int read() 입력 스트림에서 1byte씩 읽고 byte값을 int으로 반환
int read(byte[] b) 입력 스트림에서 1byte씩 읽어 byte배열에 저장, 읽은 갯수를 반환
int read(byte[] b, int off, int len) 입력 스트림에서 off부터 시작하여, len개를 읽어 byte 배열에 저장,
읽은 갯수를 반환
void close() 시스템의 자원을 반환하고 입력 스트림을 닫는다. (파일)

▶ read() 메소드

InputStream is = new FileInputStream("C:/test.jpg");
int readByte;
//모든 InputStream 하위 객체 read() : 읽은 내용이 없으면 -1 반환
while((readByte = is.read()) != -1){}

▶ 키보드에서 읽어오기 : System.in

package mymain.input;

import java.io.InputStream;

public class _01_KeyboardInputTest {

	public static void main(String[] args) throws Exception {
		int ch;
		
		//키보드의 입력값을 받는 inputStream
		//System객체 내에 포함관계로 inputStream이 생성되어 있는 상태
		InputStream is = System.in; 
		
		System.out.println("종료하려면 [Ctrl+Z]");
		
		while((ch = is.read()) != -1) {
			System.out.printf("%c",ch);
		}
	}

▶ 파일에서 읽어오기 : FileInputStream("파일경로")

package mymain.input;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class _02_FileInputTest {
	public static void main(String[] args) throws IOException {
		InputStream is = new FileInputStream("src/mymain/input/_02_FileInputTest.java");
		
		int ch;
		
		while((ch = is.read())!=-1) {
			System.out.printf("%c",ch);
		}
		
		is.close();
	}
}

▶ 네트워크에서 읽어오기 : URL(String url) > openStream()

package mymain.input;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class _03_NetWorkInputStream {
	public static void main(String[] args) throws IOException {
		URL url = new URL("https://www.naver.com");
		InputStream is = url.openStream();
		
		int ch;
		
		while((ch = is.read())!=-1) {
			System.out.printf("%c",ch);
		}
	}
}

 

(2) OutputStream 메서드

리턴타입 메소드  
void write() 출력 스트림으로 1byte씩 보낸다.
void write(byte[] b) 출력 스트림에 byte[] b의 값을 보낸다.
void write(byte[] b, int off, int len) 출력 스트림에 off부터 시작해서 len개 만큼 보낸다.
void flush() 버퍼에 잔류하는 모든 바이트를 출력
void close() 시스템의 자원을 반납하고 출력 스트림을 닫는다. (파일)

▶ read() 메소드

OutputStream os = new FileOutputStream("C:/test.txt");
byte[] data = "ABC".getBytes();
for(int i = 0; i < data.length; i++){
	os.write(data[i]);
}

 

▶ 모니터로 출력하기 : System.out

package mymain.output;

import java.io.IOException;
import java.io.OutputStream;

public class _01_MonitorTest {
	public static void main(String[] args) throws IOException {
		OutputStream os = System.out;
		
		//자바 -> 출력 스트림 -> 키보드버퍼로 문자를 전송
		os.write(65);
		
		String msg = "안녕";
		byte[] msg_bytes = msg.getBytes();
		os.write(msg_bytes);
		
		int n = 1004;
		String s = String.valueOf(n);
		os.write(s.getBytes());
		
		boolean bOk = true;
		String b = String.valueOf(bOk);
		os.write(b.getBytes());
		
		//키보드 커퍼를 비우면서 콘솔로 전송
		os.flush();
	}
}

▶ 파일로 출력하기 : FileOutputStream("파일경로");

package mymain.output;

import java.io.FileOutputStream;
import java.io.OutputStream;

public class _02_FileOutTest {

	public static void main(String[] args) throws Exception{
		OutputStream os = new FileOutputStream("a.txt");
		
		os.write('A');
		
		String name = "홍길동";
		byte[] sArr = name.getBytes();
		os.write(sArr);
		
		int n = 1994;
		os.write(String.valueOf(n).getBytes());
		
		os.flush();
		
		os.close();
	}

}

 

(3) 바이트 배열 단위로 읽어오기/보내기

가. InputStream/OutputStream의 read(byte[] b), write(byte[] b) 사용

package mymain.input;

import java.io.FileInputStream;
import java.io.InputStream;

public class _04_InputStream_Array {
	public static void main(String[] args) throws Exception{
		InputStream is = new FileInputStream("src/mymain/input/_04_InputStream_Array.java");
		
		int readByteNo;
		byte[] readBytes = new byte[8];
        //           is.read(readBytes, 1, 8); <- index 1부터 8개
		readByteNo = is.read(readBytes);
		
		for(int i = 0; i < readBytes.length; i++) 
			System.out.printf("%c",readBytes[i]);
		
		is.close();
	}
}
package mymain.output;

import java.io.FileOutputStream;
import java.io.OutputStream;

public class _03_OutputStream_Array {
	public static void main(String[] args) throws Exception{
		OutputStream os = new FileOutputStream("a2.txt");
		
		byte[] output = "ABC".getBytes();
		
		// os.write(output,1,2); /*: index1부터 2개*/
		os.write(output);
		
		os.close();
	}
}

 

나. ByteArrayInputStream/ByteArrayOutputStream 객체 사용

package mymain.input;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;

public class _04_InputStream_Array2 {
	public static void main(String[] args) throws Exception{
		byte[] inSrc = {0,1,3,4,5,6};
		byte[] outSrc = null;
		
		ByteArrayInputStream input = null;
		ByteArrayOutputStream output = null;
		
		input = new ByteArrayInputStream(inSrc);
		output = new ByteArrayOutputStream();
		
		int data = 0;

		while((data = input.read()) != -1) {
			output.write(data);
		}
		
		outSrc = output.toByteArray();
		
		System.out.println("Input Source : "+Arrays.toString(inSrc));
		System.out.println("Output Source : "+Arrays.toString(outSrc));
	}
}

>> 결과

Input Source : [0, 1, 3, 4, 5, 6]
Output Source : [0, 1, 3, 4, 5, 6]

 

 

3. 문자기반 스트림_Reader,Writer 추상클래스 상속

입력스트림 출력스트림 입출력 대상의 종류
FileReader FileWriter 파일
ByteArrayReader ByteArrayWriter 메모리(byte배열)
PipedReader PipedWriter 프로세스(프로세스간의 통신)
StringReader StringWriter 문자열
.... .... ....

 

4. 보조스트림_Filterxxxxx, Bufferedxxxxx, Objectxxxxx

입력스트림 입출력 대상의 종류
Filterxxxxx 필터를 이용한 입출력 처리
Bufferedxxxxxx 버퍼를 이용한 입출력 향상 (버퍼에 바이트/문자 올려두고, 한 줄씩 출력 가능-nextLine())
Objectxxxxxx 객체 직렬화/역직렬화

 

 

 

[참조]

이것이 자바다 

자바의 정석, 남궁성 지음