[Java][국비교육] Day 19

Ga02·2023년 1월 22일

국비교육

목록 보기
18/82

🔍 IO, 입출력

키보드 입력 ➡ 프로그램(byte[]) 저장 ➡ 모니터 출력 을 반복적으로 실행

  • 입출력 스트림별 buffer가 따로 존재 👉🏻 버퍼에 데이터들이 어느정도 모이면 입출력을 수행
  • close();를 스트림별 별도로 작성
InputStream in = System.in;
OutputStream out = System.out;

byte[] buf = new byte[1024];
int len = -1;

try {
	while( (len = in.read(buf)) != -1 ) { //EOF까지 반복적으로 입력을 받음
    	out.write(buf, 0, len);
        out.flush();
    }
} catch (IOException e) {
	e.printStackTrace();
} finally {
	
    //입력 스트림 닫기
    try {
    	if(in != null) in.close();
    } catch (IOException e) {
		e.printStackTrace();
	}

	//출력 스트림 닫기
    try {
    	if(out != null) out.close();
    } catch (IOException e) {
		e.printStackTrace();
	}

}

➰ try-catch-resource 구문

try-catch + Autoclosable interface

  • 입출력 객체 사용시 finally 블록을 이용한 close() 호출을 구문에서 자동으로 대신 처리해줌 👉🏻 try의 {} 중괄호 블록이 종료된 이후 자동으로 close()
  • try 키워드에 () 괄호를 적용 👉🏻 괄호에는 입출력 객체를 선언
    • try()에 여러 객체 선언 가능
byte[] buf = new byte[1024]; 
int len = -1; 

try(	InputStream in = System.in; 
		OutputStream out = System.out ) {

	while( (len = in.read(buf)) != -1 ) {
		
		out.write(buf, 0, len); 
		out.flush(); 
		
	}
	
} catch (IOException e) {
	e.printStackTrace();
}

🔍 class File

파일의 정보를 관리하는 클래스 👉🏻 파일의 내용물은 관리할 수 없음

  • 파일의 경로(위치, path)와 이름을 저장
  • 파일 입출력 스트림의 대상 입출력 장치로 지정할 수 있음
  • 절대경로 표기법 : root가 되는 드라이브 문자부터 파일(폴더)의 경로를 나타내는 것
  • 상대경로 표기법 : 상대적인 기준점을 출발위치로 삼아 경로를 나타내는 것
    • 프로그램이 시작된 위치를 기준으로 . 으로 표현하며 시작
      클래스 패스, class path
File file = new File("파일 경로", "파일 이름");

file.length();		/ 파일의 크기
file.exists();		/ 파일 존재여부 확인
file.isFile();		/ 파일인지?
file.isDiretory();	/ 폴더인지?

System.out.println( file );
➡ 파일의 주소 출력(파일경로/파일이름)

➰ FileInputStream

File file = new File("./src/java13_io/fileStream/", "input");

//파일 존재여부 확인
if( !file.exist() ) {
	System.out.println("[SYSTEM] 파일이 존재하지 않습니다.");
    return; //👉🏻 파일이 존재하지 않으면 main() 중단
}

//퍄일 저장 및 읽기
byte[] buf = new byte[1024];
int len = -1;
StringBuilder sb = new StringBuilder();

try( FileInputStream fis = new FileInputStream(file) ) {
	
    for((len = fis.read(buf)) != -1) {
        sb.append(new String(buf, 0, len)); //입력받은 데이터를 StringBuilder에 추가
    
    }
} catch (FileNotFoundException e) {
	e.printStackTrace();
} catch (IOException e) {
	e.printStackTrace();
}

System.out.println(sb);
//➡ 입력된 데이터 출력

➰ FileOutputStream

  • 객체생성시 매개변수로 true, false를 추가하여 모드를 변경할 수 있음
    • true : 텍스트 추가모드 👉🏻 기존 텍스트를 유지하면서 내용을 더 추가
    • false : 텍스트 쓰기모드 👉🏻 기존 내용을 지우고 새로 입력한 내용을 덮어씀
File file = new File("./src/java13_io/fileStream/", "input");

try( FileoutputStream fos = new FileOutputStream(file, true) ) {
	
    String massage = "Study hard";
    
    fos.write(massage.<getbytes(), 0, massaga.length());
    fos.flush();

} catch (FileNotFoundException e) { 
	e.printStackTrace();
} catch (IOException e) { 
	e.printStackTrace();
}
profile
IT꿈나무 댓츠미

0개의 댓글