JAVA-I/O-Basic

 

I/O

1. stream (연결통로, 입출력통로, 중간매개체)

2. stream 입출력의 크기 (음료빨대: 기본적으로 1Byte) » Byte 입출력 » Byte[] 배열

3. JAVA API가 제공하는 클래스


Byte 처리

InputStream(추상), OutputStream(추상)

두 개의 추상클래스 상속 (재정의) 클래스는

대상(memory)

ByteArrayInputStream, ByteArrayOutputStream

대상(file)

FileInputStream, FileOutputStream

추가적으로 보조 클래스

Buffer (I/O) 성능향상

BufferedInputStream, BufferedOutputStream 등등

public static void main(String[] args) {
	//Memory (배열)
	//byte (-128 ~ 127): 정수값
	byte[] inSrc = {0,1,2,3,4,5,6,7,8,9};
	//System.out.println(inSrc[5]);
	byte[] outsrc = null; //outsrc 메모리를 가지고 있지 않다
	
	ByteArrayInputStream input = null; //배열 데이터 read
	ByteArrayOutputStream output = null; //배열 데이터 write
	
	input = new ByteArrayInputStream(inSrc);
	//생성자 insrc 배열주소 read 할 수 있도록
	output = new ByteArrayOutputStream(); //write 하는 대상 (memory)
	
	System.out.println("output befre: " + Arrays.toString(outsrc));
	
	//공식같은 로직 (암기)
	int data = 0;
	while((data = input.read()) != -1 ) { //더 이상 read() 없다면 return -1
		System.out.println("data: " + data);
		//System.out.println("input.read()" +input.read());
		//input.read() 내부적으로 next() 기능을 가지고 있다
		
		output.write(data);
		//write 대상: ByteArrayOutputStream객체  read() >> write
	}
	outsrc = output.toByteArray();
	//자기가 가지고 있는 값을 배열로 만들어서
	//bye[] outsrc = null; 에게 주소값 할당
	System.out.println("outsrc: After >" + Arrays.toString(outsrc));
	}
}
//대상: File (read, write): 물리적인 파일
//FileInputStream, FileOutputStream

//txt 기반 작업: C:\\Temp\\a.txt >> HELLO
	public static void main(String[] args) {
		//1단계
		//POINT: I/O 작업은 대부분 가비지 컬렉터의 대상이 아니다
		//명시적으로 자원을 해제 작업을 한다 (함수: close() -> 소멸자 함수 호출)
		/*
		try {
			FileInputStream fs = new FileInputStream("C:\\Temp\\a.txt");
			int data = 0;
			while((data = fs.read()) != -1) {
				System.out.println("정수(숫자): " + data);
				//H read 정수값으로 반환 (아스키 코드표)
				char c = (char)data;
				System.out.println(c);
			}
		}catch (Exception e) {
			System.out.println(e.getMessage());
		}finally {
			//자원해제 (fs 변수의 scope try{ 안에서 만 }
		}
		*/
		FileInputStream fs = null;
		FileOutputStream fos = null;
		String path = "C:\\Temp\\a.txt";
		try {
			fs = new FileInputStream(path); //read
			fos = new FileOutputStream("C:\\Temp\\new.txt", true);
			//write
			//FileOutputStream 클래스는 Temp 폴더안에 new.txt가 존재하지 않으면
			//파일 생성을 합니다 >> 생성된 파일에 write 쓰기 작업
			
			//new FileOutputStream("C:\\Temp\\new.txt", true);
			//생성자 두번째 인자: true
			//기존 데이터: append
			
			//new FileOutputStream("C:\\Temp\\new.txt");
			//default: false
			//기존 데이터: overwrite
			
			
			int data = 0;
			while((data = fs.read()) != -1) {
				fos.write(data);
			}
		}catch (Exception e) {
			System.out.println(e.getMessage());
		}finally {
			//자원해제 (fs 변수의 scope try{ 안에서 만 }
			try {
				fs.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}		
	}