공부 기록/Java with ChatGPT

[Java/ChatGPT] Day 19: 예외 처리와 파일 연동 실전 연습

dev.jelee 2025. 7. 16. 15:25

[ 학습 목표 ]

  1. 파일 읽기/쓰기에서 발생할 수 있는 예외를 구체적으로 처리한다.
  2. 도서 관리 기능을 작은 프로그램처럼 구조화해서 개발한다.
  3. 지금까지 배운, 클래스, 예외, 파일 I/O, 리스트 활용 능력을 종합한다.

[ 이론 ]

1. 자주 발생하는 예외 상황

1) 파일이 존재하지 않을 경우

BufferedReader br = new BufferedReader(new FileReader("없는파일.txt"));
// → FileNotFoundException 발생

2) 파일에 쓸 수 없거나 경로가 잘못됐을 경우

BufferedWriter bw = new BufferedWriter(new FileWriter("/root/test.txt"));
// → AccessDeniedException or IOException

3) 해결 방법: 예외를 나눠서 처리하기

try {
  BufferedReader br = new BufferedReader(new FileReader("books.txt"));
  // ...
} catch (FileNotFoundException e) {
  System.out.println("파일이 존재하지 않습니다.");
} catch (IOException e) {
  System.out.println("파일 처리 중 오류 발생: " + e.getMessage());
}

2. 구조 설계 예시 (파일 연동 도서 관리 프로그램)

디렉토리 구조

📦 day19/
├── Main.java                // 실행 진입점
├── domain/
│   └── Book.java
├── service/
│   └── LibraryService.java
├── exception/
│   └── FileProcessingException.java
└── data/
    └── books.txt            // 데이터 저장 파일

3. 요구사항 정리

  • 도서를 추가하면 books.txt에 저장
  • 프로그램 실행 시 books.txt를 읽어 리스트에 담음
  • 사용자는 CLI로 다음 기능 수행:
    • 1. 도서 등록
    • 2. 도서 목록 출력
    • 3. 종료

[ 실습 ]

1. 코드 예시 (요약 구조)

1) Book.java

public class Book {
  private String title;
  private String author;
  private String year;

  // 생성자, getter, setter, toString 생략
}

2) FileProcessingException.java

public class FileProcessingException extends Exception {
  public FileProcessingException(String message) {
    super(message);
  }
}

3) LibraryService.java

public class LibraryService {
  private List<Book> books = new ArrayList<>();
  private final String FILE_PATH = "day19/data/books.txt";

  public void loadBooks() throws FileProcessingException {
    try (BufferedReader br = new BufferedReader(new FileReader(FILE_PATH))) {
      String line;
      while ((line = br.readLine()) != null) {
        String[] parts = line.split(", ");
        if (parts.length == 3) {
          books.add(new Book(parts[0], parts[1], parts[2]));
        }
      }
    } catch (IOException e) {
      throw new FileProcessingException("파일을 읽는 중 오류 발생");
    }
  }

  public void addBook(Book book) throws FileProcessingException {
    try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILE_PATH, true))) {
      bw.write(book.getTitle() + ", " + book.getAuthor() + ", " + book.getYear());
      bw.newLine();
      books.add(book);
    } catch (IOException e) {
      throw new FileProcessingException("파일을 저장하는 중 오류 발생");
    }
  }

  public void printBooks() {
    for (Book b : books) {
      System.out.println(b);
    }
  }
}

4) Main.java

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    LibraryService service = new LibraryService();

    try {
      service.loadBooks();
    } catch (FileProcessingException e) {
      System.out.println(e.getMessage());
    }

    while (true) {
      System.out.println("1. 도서 등록 | 2. 도서 목록 | 3. 종료");
      String input = sc.nextLine();

      switch (input) {
        case "1":
          System.out.print("제목: ");
          String title = sc.nextLine();
          System.out.print("저자: ");
          String author = sc.nextLine();
          System.out.print("출판연도: ");
          String year = sc.nextLine();
          try {
            service.addBook(new Book(title, author, year));
            System.out.println("등록 성공!");
          } catch (FileProcessingException e) {
            System.out.println(e.getMessage());
          }
          break;
        case "2":
          service.printBooks();
          break;
        case "3":
          System.out.println("종료합니다.");
          return;
        default:
          System.out.println("잘못된 입력입니다.");
      }
    }
  }
}

[ 과제 ]

1. 위 구조대로 프로그램을 직접 작성해보기

2. FileProcessingException을 직접 만들어서 파일 읽기/쓰기 오류 처리해보기

3. 실행 후 books.txt가 자동으로 읽히고 출력되는지 확인하기


[ 메모 ]

  • try-with-resources를 사용했다. 지난 번에 메모해서 알고는 있었는데 정확하게 명칭이 무엇인지 까먹었다. ㅠㅠ... 역시 반복이 중요한 거 같다.
  • 구조에 대해서는 보면은 이해가 되지만 아직 나 스스로가 구조를 짜기에는 힘들다. 이것도 마찬가지로 반복적으로 코드를 작성하는 것 밖에 없는 거 같다.