본문 바로가기
JAVA SE/Code

Semi Project [20.08.03/Day_18] Java SE / School Project_console_UI / IO 적용(직렬화)

by 파프리카_ 2020. 8. 3.
728x90
반응형

 

프로그램 동작 원리

 

Main Class(실행)

/TestSchoolConsoleUI.java

package school.test;

import java.io.IOException;

import school.view.ConsoleInstUI6;

public class TestSchoolConsoleUI {
	public static void main(String[] args) {
		//ConsoleInstUI2 ui = new ConsoleInstUI1();	
		//ConsoleInstUI2 ui=new ConsoleInstUI2();
		//ConsoleInstUI3 ui=new ConsoleInstUI3();
		//ConsoleInstUI4 ui=new ConsoleInstUI4();
		//ConsoleInstUI5 ui=new ConsoleInstUI5();
		ConsoleInstUI6 ui=new ConsoleInstUI6();
		try {
			ui.execute();
		} catch (ClassNotFoundException | IOException e) {
			e.printStackTrace();
		}
	}
}


 

 

I/O 를 위한 Path 잡아주는 class

/PathInfo.java

package school.model;

public interface PathInfo {
	//public static final 상수 
	String LIST_PATH="C:\\kosta203\\school\\personlist.obj";
}

 

 

Service Class(비즈니스 로직)

/SchoolService.java

package school.model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Iterator;
import java.util.LinkedHashMap;

import school.exception.DuplicateTelException;
import school.exception.PersonNotFoundException;

public class SchoolService {
	private LinkedHashMap<String, Person> map;

	/*
	 * loadList() : 역직렬화 메서드 (file -> object) 
	 * 지정한 경로 PathInfo LIST_PATH에 저장된 리스트 정보(file)를 
	 * 객체 역직렬화하여 map(object)에 로드하는 메서드 
	 * 1. 지정한 경로에 파일이 존재하는 지 유무를 확인한다 : exists() 
	 * 2. 존재하지 않으면, 구성원 정보를 저장할 맵을 생성한다. : new LinkedHashMap<String, Person>(); 
	 * 3. 존재하면 FileInputStream과 ObjectInputStream을 이용해 역직렬화하여 map에 저장한다.
	 * 4. Exception은 호출한 UI쪽으로 처리를 위임(throw/throws)한다.
	 */
	@SuppressWarnings("unchecked")
	public void loadList() throws FileNotFoundException, IOException, ClassNotFoundException {
		// 1. 파일 객체 생성
		File file = new File(PathInfo.LIST_PATH);

		// 2. 존재여부 확인 (경로가 존재하고, 파일이 존재하는지)
		if (file.exists() && file.isFile()) { // 존재하면 역직렬화
			ObjectInputStream ois = null;
			try {
				ois = new ObjectInputStream(new FileInputStream(file));
				map = (LinkedHashMap<String, Person>)ois.readObject(); //다운캐스팅
			} finally {
		    	if(ois != null)
		    		ois.close();
			}
		} else { // 존재하지 않으면, 첫 실행이므로, 저장할 map 생성
			map = new LinkedHashMap<String, Person>();
		}
	}

	/*
	 * saveList() : 직렬화 메서드 (object -> file) 
	 * 지정한 경로에 프로그램 종료 시 파일에 map을 직렬화하여
	 * 정보를 유지시키는 메서드
	 * FileOutputStream < ObjectOutputStream writeObject()
	 */	
	public void saveList() throws IOException {
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new FileOutputStream(PathInfo.LIST_PATH));
			oos.writeObject(map);
	    } finally {
	    	if(oos != null)
	    		oos.close();
	    }
	}
	
	
//tel이 중복되면 추가하지 않고 DuplicateTelException을 발생시키고 호출한 곳으로 던진다
	public void addPerson(Person person) throws DuplicateTelException {
		if (map.containsKey(person.getTel())) {
			throw new DuplicateTelException(person.getTel() + " tel이 존재하여 추가불가!");
		} else {
			map.put(person.getTel(), person);
		}
	}

	public void printAll() {
		Iterator<Person> it = map.values().iterator();
		while (it.hasNext())
			System.out.println(it.next());
	}

//tel에 해당하는 구성원이 없을 경우 PersonNotFoundException을 발생시키고
//호출한 곳으로 전달한다 
	public Person findPersonByTel(String tel) throws PersonNotFoundException {
		Person p = map.get(tel);
		if (p == null)
			throw new PersonNotFoundException(tel + " tel이 존재하지 않아 조회할 수 없습니다.!");
		return p;
	}

	public Person removePersonByTel(String tel) throws PersonNotFoundException {
		Person p = map.remove(tel);
		if (p == null)
			throw new PersonNotFoundException(tel + " tel이 존재하지 않아 삭제할 수 없습니다.! ");
		return p;
	}

	public void updatePerson(Person person) throws PersonNotFoundException {
		if (map.containsKey(person.getTel()) == false)
			throw new PersonNotFoundException(person.getTel() + " tel이 존재하지 않아 수정할 수 없습니다.! ");
		map.put(person.getTel(), person);
	}
}

 

 

View/UI Class(Console UI)

/ConsoleInstUI6.java

package school.view;

import java.io.IOException;
import java.util.Scanner;

import school.exception.DuplicateTelException;
import school.exception.PersonNotFoundException;
import school.model.Employee;
import school.model.Person;
import school.model.SchoolService;
import school.model.Student;
import school.model.Teacher;

//구성원 추가 및 전체회원보기, 검색 , 삭제
//구성원 추가시 전화번호 tel 입력받을 때 바로 중복확인 체크 로직 추가
public class ConsoleInstUI6 {
	private SchoolService service = new SchoolService();
	private Scanner scanner = new Scanner(System.in);

	public void execute() throws ClassNotFoundException, IOException {
		try {
			//SchoolService의 loadLIst()메서드를 호출하여 프로그램 실행 첫 시점에 구성원 명단을 로드한다
			service.loadList();
			System.out.println("*******학사관리프로그램을 시작합니다 ver6******");
			
			// 제어문 label --> 아래 5 종료시 break만 명시하면 해당 switch문만
			// 벗어나므로 아래 while문 전체를 벗어나야 프로그램이 종료되므로
			// 레이블을 이용한다
			exit: while (true) {
				System.out.println("1. 추가 2. 삭제 3. 검색 4. 전체회원보기 5.종료");
				String menu = scanner.nextLine();// 사용자로부터 메뉴번호를 입력받는다
				switch (menu) {
				case "1":
					addView();
					break;
				case "2":
					deleteView();
					break;
				case "3":
					findView();
					break;
				case "4":
					System.out.println("**전체구성원보기**");
					service.printAll();
					break;
				case "5":
					System.out.println("*******학사관리프로그램을 종료합니다******");
					//종료 시, schoolService의 saveList()를 호출해서 구성원 정보를
					//직렬화하여 파일에 저장한다.
					service.saveList();
					break exit;// while문을 벗어나도록 레이블을 사용한다
				default: // 1~5 아닌 값은 default에서 처리
					System.out.println("잘못된 입력값입니다!");
				}// switch
			} // while
		} finally {
			scanner.close();
		}
	}// execute method
		// 구성원 추가 작업을 담당하는 메서드

	public void addView() {
		String menu = null;
		while (true) {
			System.out.println("입력할 구성원의 종류를 선택하세요 1.학생  2.선생님 3.직원");
			menu = scanner.nextLine();
			if (menu.equals("1") || menu.equals("2") || menu.equals("3"))
				break;
			else
				System.out.println("학생,선생님,직원(1~3번) 중 하나의 메뉴를 선택하세요!");
		}

		String tel = null;
		while (true) {
			System.out.println("1. 전화번호를 입력하세요!");
			tel = scanner.nextLine();
			// tel 중복확인 로직을 추가
			try {
				service.findPersonByTel(tel);
				System.out.println("전화번호가 중복됩니다. 다시 입력하세요!");
			} catch (PersonNotFoundException e) {
				break; //전화번호가 없으면 해당 while문을 벗어난다
			}			
		} // while
		System.out.println("2. 이름을 입력하세요!");
		String name = scanner.nextLine();
		System.out.println("3. 주소를 입력하세요!");
		String address = scanner.nextLine();
		Person person = null;
		switch (menu) {
		case "1":
			System.out.println("4. 학번을 입력하세요!");
			String stuId = scanner.nextLine();
			person = new Student(tel, name, address, stuId);
			break;
		case "2":
			System.out.println("4. 과목을 입력하세요!");
			String subject = scanner.nextLine();
			person = new Teacher(tel, name, address, subject);
			break;
		case "3":
			System.out.println("4. 부서를 입력하세요!");
			String dept = scanner.nextLine();
			person = new Employee(tel, name, address, dept);
			break;
		}
		try {
			service.addPerson(person);
			System.out.println("리스트에 추가:" + person);
		} catch (DuplicateTelException e) {
			System.out.println(e.getMessage());
		}
	}// addView method

	public void findView() {
		System.out.println("조회할 구성원의 전화번호를 입력하세요");
		String tel = scanner.nextLine();
		try {
			Person p = service.findPersonByTel(tel);
			System.out.println("조회결과:" + p);
		} catch (PersonNotFoundException e) {
			System.out.println(e.getMessage());
		}
	}// find method

	public void deleteView() {
		System.out.println("삭제할 구성원의 전화번호를 입력하세요");
		String tel = scanner.nextLine();
		try {
			service.removePersonByTel(tel);
			System.out.println(tel + "에 해당하는 구성원을 삭제하였습니다.");
		} catch (PersonNotFoundException e) {
			System.out.println(e.getMessage());
		}
	}// delete method
}// class

 

 

Exception Class

/DuplicateTelException.java

package school.exception;

public class DuplicateTelException extends Exception{
	private static final long serialVersionUID = -4777520156818321640L;
	public DuplicateTelException(String message){
		super(message);
	}
}

 

/PersonNotFoundException.java

package school.exception;

public class PersonNotFoundException extends Exception {
	private static final long serialVersionUID = 2058608171294523577L;

	public PersonNotFoundException(String message) {
		super(message);
	}
}

 

 

VO Class

/Person.java

package school.model;

import java.io.Serializable;

public class Person implements Serializable{
	private static final long serialVersionUID = -1930947604867574732L;
	private String tel;
	private String name;
	private String address;
	public Person(String tel, String name, String address) {
		super();
		this.tel = tel;
		this.name = name;
		this.address = address;
	}
	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	@Override
	public String toString() {
		return "tel=" + tel + ", name=" + name + ", address=" + address;
	}
	
}

 

/Student.java

package school.model;

public class Student extends Person {
	private static final long serialVersionUID = 1L;
	private String stdId;
	public Student(String tel, String name, String address, String stdId) {
		super(tel, name, address);
		this.stdId = stdId;
	}
	
	public String getStdId() {
		return stdId;
	}

	public void setStdId(String stdId) {
		this.stdId = stdId;
	}

	@Override
	public String toString() {
		return super.toString()+" stdId=" + stdId;
	}	
}

 

/Teacher.java

package school.model;

public class Teacher extends Person{
	private static final long serialVersionUID = 6318038335031650044L;
	private String subject;
	public Teacher(String tel, String name, String address, String subject) {
		super(tel, name, address);
		this.subject = subject;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	@Override
	public String toString() {
		return super.toString()+" subject=" + subject;
	}	
}

 

/Employee.java

package school.model;

public class Employee extends Person{
	private static final long serialVersionUID = 1L;
	private String department;
	public Employee(String tel, String name, String address, String department) {
		super(tel, name, address);
		this.department = department;
	}
	public String getDepartment() {
		return department;
	}
	public void setDepartment(String department) {
		this.department = department;
	}
	@Override
	public String toString() {
		return super.toString()+" department=" + department;
	}
	
}

 

 

728x90
반응형