국비지원 복습과정 13차 (catch 블록을 사용한 복합 에러처리, file만들기)

Park In Kwon·2022년 9월 15일
0

1. catch 블록을 사용한 복합 에러처리

  • catch 블록은 에러가 예상되는 상황에 대해 복수로 명시하는 것이 가능하다.

1-1. Exception Class

  • Java에서 예외 상황을 의미하는 모든 클래스들의 최상위 클래스
  • 이 클래스의 이름으로 catch 블록을 구성하면, 모든 예외 상황에 일괄적으로 대응할 수는 있지만, catch 블록이세분화 된 경우와는 달리 상황 별 개별적인 처리는 불가능하다.
  • Exception 클래스에 대한 예외처리는 대부분 맨 마지막 catch 블록에 명시하여 '마지막 알 수 없는 에러'
    를 의미하도록 구성한다.
   try {
                 ....
   } catch ( NumberFprmatException e ) {
                 ....
   } catch ( ArrayIndexOutOfException e ) {
                 ....
   } catch ( Exception e ) {
                 ....
   }
  • 자바 1.8 버전 지원
      try {
                 ....
     } catch ( NumberFprmatException | ArrayIndexOutOfException e ) {
                 ....
     } catch ( Exception e ) {
                 ....
     }

1-2. 에러 객체 'e' 의 기능

  • e.getMessage( )
    -> 간략한 에러 메시지를 리턴한다.
    -> e.getLocaliseMessage( ) 도 같은 기능을 한다.
  • e.printStackTrace( )
    -> 실제 예외 상황시에 출력되는 메세지를 강제로 출력한다.
    -> 개발자가 catch 블록 안에서 예외 상황을 분석하기 위한 용도로 사용한다.

file

package file;

import java.io.File;

public class Main01 {

	public static void main(String[] args) {
		//File클래스는 절대경로나, 상대경로를 생성자 파라미터로 전달한다.
		// 이클립스에서 상대경로를 사용할 경우, 현재 프로젝트가 기준점이 된다.
		// Workspace가 C:/java 이고, 프로젝트가 'day20'인 경우의 작업 위치는
		// C:/java/day20 
		File file = new File("src/file/Main01.java");
		
		// 전달된 경로가 파일인지 검사
		// -> 존재하지 않는 파일로 검사할 경우 무조건 false가 된다.
		boolean is_file = file.isFile();
		System.out.println("is_file : " + is_file);
		
		//전달된 경로가 디렉토리인지 검사
		// -> 존재하지 않는 디렉토리로 검사할 경우 무조건 false
		boolean is_dir = file.isDirectory();
		System.out.println("is_dir : " + is_dir);
		
		//전달된 경로가 숨김 형태인지 검사
		// -> 존재하지 않는 파일로 검사할 경우 무조건 flase
		boolean is_hidden = file.isHidden();
		System.out.println("is_hidden : " + is_hidden);
		
		//절대 경로 값을 추출
		String abs = file.getAbsolutePath();
		System.out.println("절대경로 : " + abs);
		
		// 생성자에 전달된 파일이나 디렉토리가 물리적으로 존재하는지를 검사
		boolean is_exist = file.exists();
		System.out.println("존재 여부 : " + is_exist);
		
		System.out.println("-----------------------");
		
		// 디렉토리 정보 객체 생성
		File file2 = new File("a/b/c/target");
		System.out.println("isFile : " + file2.isFile());
		System.out.println("isDirectory : " + file2.isDirectory());
		System.out.println("isHidden : " + file2.isHidden());
		System.out.println("절대경로 : " + file2.getAbsolutePath());
		System.out.println("존재여부 : " + file2.exists());
		
		//경로에 따른 디렉토리 생성
		file2.mkdirs();
		
		System.out.println("---------------------");
		
		//마지막 "/" 이후 단어를 리턴
		System.out.println(file.getName()); 
		System.out.println(file2.getName()); 
		
		//처음부터 마지막 "/" 직전까지 리턴
		System.out.println(file.getParent()); 
		System.out.println(file2.getParent()); 
		
		// 삭제 시도 -> 성공 시 true, 실패 시 false
		boolean del_ok = file2.delete();
		System.out.println("삭제 성공 여부 : " + del_ok);
	}
}

package file;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

public class Main02 {

	public static void main(String[] args) {
		/*
		 * 문자열을 파일로 저장
		 *  -> 문자열을 파일로 저장하기 위해서는 byte 배열로 변환해야 한다.
		 *  -> 문자열을 byte배열로 변환하기 위해서는 getBytes() 메서드를 사용하는데,
		 *  이 때 변환 과정에서 사용할 인코딩 형식을 지정해주어야 한다.
		 */
		
		// 저장할 파일의 경로
		String path = "text.txt";
		
		// 파일에 저장할 내용
		String write_string = "오늘피곤하구만abcdefg";
		
		//특정 인코딩 방식 적용
		// 객체나 배열이 선언과 할당에 대한 블록이 서로 분리되어 있을 경우
		// 명시적으로 빈 영역임을 알리기 위하여 null로 초기화
		
		byte[] buffer = null;
		
		try {
			buffer = write_string.getBytes ("utf-8");
		} catch (UnsupportedEncodingException e) {
			System.out.println("[ERROR] 알 수 없는 인코딩 정보>> " + path);
			e.printStackTrace();
		}
		
		//파일 저장 절차 시작
		// finally 블록에서 인식하기 위해서 선언부를 위로 이동시킨다.
		OutputStream out = null;
		
		try {
			out = new FileOutputStream(path);
			// 파일쓰기
			out.write(buffer);
			System.out.println("[INFO]파일 저장 성공 >> " + path);
		} catch (FileNotFoundException e) {
			System.out.println("[ERROR] 지정된 경로를 찾을 수 없음>> " + path);
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("[ERROR] 파일 저장 실패 >> " + path);
			e.printStackTrace();
		} catch (Exception e) {	
			System.out.println("[ERROR] 알 수 없는 에러>> " + path);
			e.printStackTrace();
		} finally {
			// 저장의 성공여부에 상관없이 스트림은 무조건 닫아야 한다.
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

package file;

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

public class Main03 {

	public static void main(String[] args) {
		// 읽을 파일 경로
		String path = "text.txt";
		
		//읽은 내용이 담겨질 스트림
		byte[] data = null;
		
		//읽은 내용이 변환될 문자열
		String read_string = null;
		
		//파일 읽기
		InputStream in = null;
		
			try {
				in = new FileInputStream(path);
				//읽은 내용을 담기 위한 파일의 용량만큼 사이즈를 할당한다
				// in.available(); -> 열고 있는 파일의 크기
				data = new byte[in.available()]; 
				// 파라미터로 전달된 배열 안에, 파일의 내용을 담아준다.
				in.read(data); 
				System.out.println("[INFO] 파일 읽어오기 성공 >> " + path);
			} catch (FileNotFoundException e) {
				System.out.println("[ERROR] 지정된 경로를 찾을 수 없음 >> " + path);
				e.printStackTrace();
			} catch (IOException e) {
				System.out.println("[ERROR] 파일 읽기 실패 >> " + path);
				e.printStackTrace();
			} catch (Exception e) {
				System.out.println("[ERROR] 알 수 없는 에러 >> " + path);
				e.printStackTrace();
			} finally {
				if (in != null) {
					 try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			// data 배열에 내용이 있다면, 문자열로 변환하여 출력
			if (data != null) {
				// 문자열로 변환시에는 저장된 인코딩으로 지정해 준다.
				try {
					read_string = new String(data, "utf-8");
					System.out.println(read_string);
				} catch (UnsupportedEncodingException e) {
					System.out.println("[ERROR] 인코딩 지정 에러 >> " + path);
					e.printStackTrace();
				} 
			} 
		} 
}
profile
개발자로 진로 변경을 위해 준비하고 있습니다

0개의 댓글