[til 016_001]

김동현·2023년 8월 7일
0

til

목록 보기
29/53

io 부분 복습중 구글링으로 찾아본것을 기록하려 한다.

try catch 문에서 데이터를 쓰는 작업을 수행했다면 지금까지는 finally 블록에서 스트림을 닫아주는 (close()) 과정을 수행했었다.

이는 입출력 작업시 한정된 외부 리소스를 닫지않고 계속 누적한다면 문제가 발생하기 때문인데

try-with-resource 문을 사용하면 리소스를 자동으로 해제할 수 있다고 한다.

try (OutputStream outputStream = new FileOutputStream("file.txt")) {
// 데이터를 파일에 쓰는 작업
} catch (IOException e) {
// 예외 처리
}

위의 코드에서는 예외가 발생하더라도 outputstream 을 자동으로 닫아주게되어 finally블록을 사용하지 않아도 된다고 한다.

public void output1() {
	
	// 바이트 기반 스트림 이용
	
	FileOutputStream fos = null;
	
	// FileOutputStream 객체 생성 시
	// FileNotFoundException / IOException 예외가 발생할 가능성이 있음 -> 예외처리 필요
	
	try {
		
		fos = new FileOutputStream("test1.txt");
		// 현재 프로그램에서 test1.txt 파일로 출력하는 통로 객체 생성
		
		// 파일에 "Hello" 내보내기
		String str = "Hello";
		
		for(int i = 0; i< str.length(); i++) {
			// "hello"를 한문자씩 끊어서 파일로 출력하기
			
			fos.write(str.charAt(i));
			
			// write()는 IOException을 발생시킬 가능성이 있다.
			
		}
		
		
	}catch (IOException e) {
		System.out.println("예외 발생");
		// 예외 추적
		e.printStackTrace();
	} finally {
		// 예외가 발생 하든 말든 무조건 수행
		// 사용한 스트림 자원 반환(통로 없에야함) --> 필수 작성!!!
		// 프로그램 메모리 관리 차원에서 항상 다쓰면 끊어줌
		// -> 작성 안하면 문제점으로 꼽을 수 있다!
		
		try {
		
			fos.close();
					
		} catch (IOException e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}
}

이렇게 사용했던 것을

public void output3() {
	
	
	
	String str = "Hello";
	
	
	try (FileOutputStream fos = new FileOutputStream("test1.txt")){
		
		
		
		for(int i = 0; i< str.length(); i++) {
			
			fos.write(str.charAt(i));
			
			
		}
		
		
	}catch (IOException e) {
		System.out.println("예외 발생");
		e.printStackTrace();
		
		
					
	}
}

이런식으로 수정해 볼 수 있었다.

public void input1() {

	FileInputStream fis = null;
	// 파일 -> 프로그램으로 읽어오는 바이트 기반 스트림
	
	try {
		fis = new FileInputStream("test1.txt");
		// FileInputStrem 은 1byte 씩만 읽어올 수 있다.
		
		while(true) {
			int data = fis.read(); // 다음 1byte를 읽어오는데 정수형임.
			// 다음 내용이 없으면 -1 반환
			
			if(data == -1) { // 다음 내용 없음 -> 종료
				break;
			}
			// 반복종료가 안됐으면 char로 강제 형변환하여 문자로 출력
			System.out.print((char)data);
		}
		
	} catch (IOException e) {
		
		e.printStackTrace();
		
	} finally {
		try {
			fis.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}

전에 작성했던 input 연습도

public void input1() {
// 파일 -> 프로그램으로 읽어오는 바이트 기반 스트림
try (FileInputStream fis = new FileInputStream("test1.txt")) {
    // FileInputStrem은 1byte 씩만 읽어올 수 있다.

    while (true) {
        int data = fis.read(); // 다음 1byte를 읽어오는데 정수형임.
        // 다음 내용이 없으면 -1 반환

        if (data == -1) { // 다음 내용 없음 -> 종료
            break;
        }
        // 반복종료가 안됐으면 char로 강제 형변환하여 문자로 출력
        System.out.print((char) data);
    }

} catch (IOException e) {
    e.printStackTrace();
}
}

이렇게 수정할 수 있다.

0개의 댓글

관련 채용 정보