고급JAVA 11강 - 입출력

Whatever·2021년 11월 11일
0

고급 JAVA

목록 보기
11/32

입출력

입력: 프로그램으로 데이터가 들어가는 것
출력: 그 데이터를 다른 곳으로 보내는 것

스트림 : 데이터가 왔다갔다하는 흐름, 데이터를 입출력하는데 사용하는 연결통로
자바는 스트림객체를 이용해서 입출력을 함.

1.2 바이트기반 스트림 – InputStream, OutputStream

  • 데이터를 바이트(byte)단위로 주고 받는다.
    메서드

    abstract int read() - 바이트로 읽어서 int로 반환
    int read(byte[] b) - 배열 크기만큼 읽어들임 => 실제 읽어온 개수 반환
    int read(byte[] b, int off, int len) - len : 읽어올 개수, 배열에 저장해서 배열의 off번째부터 저장
    =>반환값은 실제 읽어온 개수

    abstract void write(int b) => 파라미터는 출력할 대상
    void write(byte[] b)
    void write(byte[] b, int off, int len) - byte배열 b에서 off번째부터 출력하라

1.3 보조스트림

  • 스트림의 기능을 향상시키거나 새로운 기능을 추가하기 위해 사용
  • 독립적으로 입출력을 수행할 수 없다.
  • 기반 스트림은 실제 입출력을 하고 보조스트림은 입출력을 할 때 도움을 줌
    대표적인 것은 BufferedInputStream, BufferedOutputStream

1.4 문자기반 스트림 – Reader, Writer

2.1 InputStream과 OutputStream
▶ InputStream(바이트기반 입력스트림의 최고 조상)의 메서드
int available() -
void close() - 스트림 닫기
void mark() - 현재 위치 표시하기
boolean markSupported() - mark()와 reset()을 지원하는지 알기
abstract int read()
int read(byte [] b)
int read(byte [] b, inf off, int len)
void reset()
long skip(long n)

▶ OutputStream(바이트기반 출력스트림의 최고 조상)의 메서드

Buffer - cpu보다는 느리지만 printer보다는 빠른 장치
cpu의 속도를 printer가 따라오지 못해서 중간에 buffer를 둬서 일을 처리하게 하고 cpu는 다음 일로 넘어감
buffer는 가득 채워져야 printer로 보내고나서 buffer가 비워짐
=> 가득차지 않으면 출력이 안되기때문에 강제적으로 모든 내용을 출력하게 하는 메서드 필요- flush()

12 ==> 00001100
-12 ==> 10001100(x)
00001100
11110011
1

----------
11110100   ==> -12	
00001011
          1
----------
00001100	

컴퓨터의 음수는 2의 보수법으로 표현한다.
2의보수 = 1의보수 + 1

0 ==> 000000000
11111111
1

     ----------
    100000000			

-1 00000001
11111111

int는 4byte이기 때문에
00000000 00000000 00000000 111111111

8비트는 -128~127까지 표현 가능

바이트기반

package kr.or.ddit.basic;

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

public class ByteArrayIOTest01 {

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 ) {
		output.write(data); //읽어온 데이터를 그대로 출력한다.
		
	}
	
	//출력된 스트림 값들을 배열로 반환해서 저장하기
	outSrc = output.toByteArray();
	
	try {
		input.close();
		output.close();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	System.out.println(" inSrc => " + Arrays.toString(inSrc));
	System.out.println("outSrc => " + Arrays.toString(outSrc));
	
}

}

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); //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
	}
			
	

}

}

파일기반

public class FileIOTest01 {

public static void main(String[] args) {
	
	try {
		//파일 내용을 읽기 위해서는 FileInputStream객체가 필요하다.
		
		//스트림 객체 생성
		//방법1 ==> 읽어올 파일 정보를 문자열로 직접 기술하는 방법

// FileInputStream fin = new FileInputStream("d:/d_Other/test.txt");

		//방법2 ==> 읽어올 파일을 File 객체로 만들어서 사용하는 방법
		File file = new File("d:/d_Other/test.txt");
		FileInputStream fin = new FileInputStream(file);
		
		int c; //읽어온 데이터가 저장될 변수
		while((c = fin.read()) != -1) { //읽어올 게 없으면 -1 반환, while문을 빠져나옴
			//읽어온 데이터를 화면에 출력하기
			System.out.print((char)c);
			
		}
		
		fin.close(); // 작업 완료 후 스트림 닫기
		
		
	} catch (IOException e) {
		// TODO: handle exception
	}
}

}
public class FileIOTest02 {

public static void main(String[] args) {
	// 파일에 데이터 출력하기
	
	try {
		FileOutputStream fout = new FileOutputStream("d:/d_other/out.txt");

//없으면 새로만들어지고 있으면 덮어써짐

		for(char ch='A'; ch<='Z'; ch++) {
			fout.write(ch); //ch변수의 데이터를 파일로 출력한다.
		}
		
		System.out.println("출력 작업 완료!!!");
		fout.close(); //쓰기 작업 완료 후 스트림 닫기
		
	} catch (IOException e) {
		// TODO: handle exception
	}

}

}

public class FileIOTest03 {

public static void main(String[] args) {
	// 문자 기반의 스트림을 이용한 파일 내용 읽어와 출력하기
	// 영어가 아닌 문자들은 바이트 기반으로 읽어오면 깨질 수 있음 => 문자버전으로 읽기
	try {
		FileReader fr = new FileReader("d:/d_other/test.txt");
		
		int c;
		
		while((c=fr.read()) != -1) {
			System.out.print((char)c);
		}
		
		fr.close();
		
	} catch (IOException e) {
		// TODO: handle exception
	}
	

}

}

public class FileIOTest04 {

public static void main(String[] args) {
	// 사용자가 입력한 내용을 그대로 파일로 저장하기
	
	try {

// Scanner scan = new Scanner(System.in); //표준입력장치를 입력할 때 만드는 입력스트림
//보조스트림, 바이트기반의 스트림을 문자스트림으로 바꿔줌
// System.in ==> 콘솔(표준입출력장치)의 입력장치용 스트림객체
// InputStreamReader
// ==> 입력용 바이트기반의 스트림을 문자기반의 스트림으로 변환하는 보조스트림이다.
InputStreamReader isr = new InputStreamReader(System.in);

		// 파일 출력용 문자기반 스트림객체 생성
		FileWriter fw = new FileWriter("d:/d_other/testChar.txt");
		
		System.out.println("아무 내용이나 입력하세요.(입력의 끝은 Ctrl + Z 입니다.)");
		
		int c;
		
		// 콘솔에서 입력할 때 입력의 끝은 'Ctrl + Z'키를 누르면 된다. 
		while((c = isr.read()) != -1) {
			fw.write(c); // 콘솔로 입력한 데이터를 파일로 출력한다.
		}
		
		//스트림 닫기
		isr.close();
		fw.close();
		
	} catch (IOException e) {
		// TODO: handle exception
	}

}

}

public class FileIOTest05 {

public static void main(String[] args) {
	// 한글 내용이 있는 파일 읽어오기
	// (한글의 인코딩 방식을 지정해서 읽어오기)
	
	try {
		//FileReader fr = new FileReader("d:/d_other/test_ansi.txt");
		//FileReader fr = new FileReader("d:/d_other/test_utf8.txt");
		
		//FileInputStream fin = new FileInputStream("d:/d_other/test_ansi.txt");
		FileInputStream fin = new FileInputStream("d:/d_other/test_utf8.txt");
		
		// 기본 인코딩 방식으로 읽어온다.
		//InputStreamReader isr = new InputStreamReader(fin);
		
		// 인코딩 방식을 지정해서 읽어오기
		// 인코딩 방식 예시
		// - MS949 ==> 윈도우의 기본 한글 인코딩 방식(ANSI방식과 같다.)
		// - UTF-8 ==> 유니코드 UTF-8 인코딩 방식
		// - US-ASCII ==> 영문 전용 인코딩 방식
		
		//InputStreamReader isr = new InputStreamReader(fin, "ms949");
		InputStreamReader isr = new InputStreamReader(fin, "utf-8");
		
		
		int c;
		while((c=isr.read())!= -1) {
			System.out.print((char)c);
		}
		
		isr.close();
		
		
	} catch (IOException e) {
		// TODO: handle exception
	}

}

}

/
문제)
d:/dother폴더에 저장되어 있는 '펭귄.jpg'파일을 'd:/d_other/연습용' 폴더에
'복사본
펭귄.jpg'파일로 복사하는 프로그램을 작성하시오.
/
public class FileCopyTest {

public static void main(String[] args) {
	
	//스트림 객체 생성
	
	try {
		//펭귄.jpg파일 불러오기
		File file = new File("d:/d_other/펭귄.jpg");
		FileInputStream fin = new FileInputStream(file);
		//파일객체 생성
		FileOutputStream fout = new FileOutputStream("d:/d_other/연습용/복사본_펭귄.jpg");
		
		int c;
		
		//펭귄.jpa파일 읽어서 붙여넣기
		while((c=fin.read())!=-1) {
			fout.write(c);
		}
		
		fin.close();
		fout.close();
		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	
	
}

}

                              

0개의 댓글