728x90
반응형
■ Customer.java
package jun.cms.vo;
import java.io.Serializable;
// 슈퍼 클래스, 유징 필드, 게터 세터, 투스트링
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
// 멤버필드
private String name;
private int age;
private String tel;
private String address;
// 생성자
public Customer() {
}
public Customer(String name, int age, String tel, String address) {
super();
this.name = name;
this.age = age;
this.tel = tel;
this.address = address;
}
// 메서드
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Customer [name=" + name + ", age=" + age + ", tel=" + tel + ", address=" + address + "]";
}
}
■ CustomerManager.java
package jun.java.exam05;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import jun.cms.vo.Customer;
public class CustomerManager {
// 멤버필드
private boolean isLoop;
private BufferedReader br;
private ArrayList<Customer> data;
private int position;
private File file;
//생성자
public CustomerManager() {
isLoop = true;
br = new BufferedReader(new InputStreamReader(System.in));
data = new ArrayList<Customer>();
position = -1;
file = null;
}
// 메서드
/**
* 고객관리 프로그램을 시작 메뉴를 출력해주는 기본 메서드
*/
public void start() throws IOException {
int menu = -1;
while(isLoop) {
System.out.println("1. 고객등록");
System.out.println("2. 고객검색");
System.out.println("3. 고객정보수정");
System.out.println("4. 고객정보삭제");
System.out.println("5. 전체고객목록보기");
System.out.println("6. 새파일");
System.out.println("7. 불러오기");
System.out.println("8. 저장하기");
System.out.println("9. 새이름으로 저장하기");
System.out.println("0. 프로그램종료");
System.out.print("메뉴선택 : ");
try {
menu = Integer.parseInt(br.readLine());
} catch(NumberFormatException nfe) {
menu = -1;
}
switch(menu) {
case 1: addCustomer(); break;
case 2: searchCustomer(); break;
case 3: updateCustomer(); break;
case 4: deleteCustomer(); break;
case 5: displayCustomer(); break;
case 6: newFile(); break;
case 7: openFile(); break;
case 8: saveFile(); break; // 홍길동/20/010/율도국 형식으로 저장해야 함
case 9: saveAsFile(); break;
case 0: stop(); break;
default:
System.err.println();
System.err.println("메뉴 선택 오류 : 메뉴를 확인하시고 다시 입력해 주세요");
}
System.out.println();
}
}
private void newFile() throws IOException{
System.out.println();
System.out.println("새로운 파일을 만드시면 기존의 데이터가 삭제됩니다.");
System.out.println("혹시 저장을 안 하셨다면 취소하시고 기존 데이터를 저장하세요.");
System.out.print("새로운 파일에 작업을 하시겠습니까? (y/n) : ");
String result = br.readLine();
if(result.equals("Y") || result.equals("y")) {
file = null;
data.clear();
System.out.println("새로운 파일로 작업을 시작합니다.");
} else {
System.out.println("새로운 파일로 작업을 취소합니다.");
}
}
private void openFile() throws IOException{
System.out.println();
System.out.println("불러올 파일명을 경로와 확장자까지 정확하게 입력하세요.");
System.out.println("취소하시면 숫자 0을 입력하세요.");
System.out.print("파일명 (취소:0) = ");
String fileName = br.readLine();
if(fileName.equals("0")) {
System.out.println("데이터 로드를 취소합니다.");
return;
}
file = new File(fileName);
// loadData();
loadDataObject();
}
private void saveFile() throws IOException{
System.out.println();
if(file == null) {
System.out.println("저장할 파일명을 경로와 확장자까지 정확하게 입력하세요.");
System.out.println("취소하시려면 숫자 0을 입력하세요");
System.out.print("파일명 (취소:0) = ");
String fileName = br.readLine();
if(fileName.equals("0")) {
System.out.println("데이터 저장을 취소합니다.");
return;
}
file = new File(fileName);
}
// saveData();
saveDataObject();
}
private void saveAsFile() throws IOException{
System.out.println();
System.out.println("저장할 파일명을 경로와 확장자까지 정확하게 입력하세요.");
System.out.println("취소하시려면 숫자 0을 입력하세요");
System.out.print("파일명 (취소:0) = ");
String fileName = br.readLine();
if(fileName.equals("0")) {
System.out.println("데이터 저장을 취소합니다.");
return;
}
file = new File(fileName);
// saveData();
saveDataObject();
}
private void loadDataObject() {
data.clear();
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
Customer myCustomer = null;
while((myCustomer = (Customer) ois.readObject()) != null) {
data.add(myCustomer);
}
} catch(ClassNotFoundException cnfe) {
System.err.println("클래스 이름에 오타가 있습니다.");
} catch(EOFException eofe) {
System.out.println(file.getName() + "파일에서 데이터를 로딩했습니다.");
} catch(FileNotFoundException fnfe) {
System.err.println("파일이름 또는 경로가 잘못되었습니다.");
} catch(IOException ioe) {
ioe.printStackTrace();
} finally {
try {if(ois != null) ois.close();} catch(IOException ioe) {}
try {if(fis != null) fis.close();} catch(IOException ioe) {}
}
}
private void saveDataObject() {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
for (Customer myCustomer : data) {
oos.writeObject(myCustomer);
}
System.out.println(file.getName() + "파일에 데이터를 성공적으로 저장했습니다.");
} catch(FileNotFoundException fnfe) {
System.out.println("해당 경로가 잘못되었습니다.");
} catch(IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if(oos != null) oos.close();
} catch(IOException ioe) {
}
try {
if(fos != null) fos.close();
} catch(IOException ioe) {
}
}
}
private void loadData() {
data.clear(); // 데이터가 누적되지 않게 기존의 데이터를 지워줌.
FileReader fr = null;
BufferedReader brfile = null;
try {
brfile = new BufferedReader(fr);
String imsiData = "";
while((imsiData = brfile.readLine()) != null) {
String[] temp = imsiData.split("/");
Customer myCustomer = new Customer(temp[0], Integer.valueOf(temp[1]), temp[2], temp[3]);
data.add(myCustomer);
}
System.out.println(file.getName() + "파일에서 데이터를 로딩했습니다.");
} catch(FileNotFoundException fnfe) {
System.err.println("파일이름 또는 경로가 잘못되었습니다.");
} catch(IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if(brfile != null)
brfile.close();
} catch(IOException ioe) {
}
try {
if(fr != null)
fr.close();
} catch(IOException ioe) {
}
}
}
private void saveData() {
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter pw = null;
try {
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
pw = new PrintWriter(bw, true);
for(int i=0; i<data.size(); i++) {
Customer myCustomer = data.get(i);
StringBuffer sb = new StringBuffer();
sb.append(myCustomer.getName());
sb.append("/");
sb.append(myCustomer.getAge());
sb.append("/");
sb.append(myCustomer.getTel());
sb.append("/");
sb.append(myCustomer.getName());
sb.append("/");
sb.append(myCustomer.getAddress());
pw.println(sb.toString());
}
System.out.println(file.getName() + "파일에 데이터를 성공적으로 저장했습니다.");
} catch(FileNotFoundException fnfe) {
System.err.println("해당 경로가 잘못되었습니다.");
} catch(IOException ioe) {
ioe.printStackTrace();
} finally {
if(pw != null)
pw.close();
try {
if(bw != null)
bw.close();
} catch(IOException ioe) {
}
try {
if(fw != null)
fw.close();
} catch(IOException ioe) {
}
}
}
// 고객관리 프로그램을 종료해주는 메서드
private void stop() throws IOException{
System.out.println();
System.out.print("정말로 종료하시겠습니까? (y/n) : ");
String result = br.readLine();
if(result.equals("Y") || result.equals("y")) {
isLoop = false;
System.out.println("프로그램을 종료합니다.");
}
}
// data라는 ArrayList에 등록된 고객 전체 목록을 출력해주는 메서드
private void displayCustomer() {
System.out.println();
// for(int i=0; i<data.size(); i++)
for(Customer myCustomer : data) // 향상된 for문
System.out.println(myCustomer.toString());
}
private void deleteCustomer() throws IOException {
System.err.println();
if(position < 0) {
System.out.println("고객 검색을 먼저 수행하셔야 합니다.");
return;
}
Customer myCustomer = data.get(position);
System.out.print(myCustomer.getName() + "님의 정보를 정말로 삭제하시겠습니까? (y/n) : ");
String result = br.readLine();
if(result.equals("Y") || result.equals("y")) {
data.remove(position);
position = -1;
System.out.println(myCustomer.getName() + "님의 정보를 성공적으로 삭제했습니다.");
} else {
System.out.println(myCustomer.getName() + "님의 정보삭제를 취소합니다.");
}
}
private void updateCustomer() throws IOException{
System.err.println();
if(position < 0) {
System.err.println("고객 검색을 먼저 수행하셔야 합니다.");
return;
}
int menu = -1;
boolean isStop = false;
Customer myCustomer = data.get(position);
while(!isStop) {
System.out.println(myCustomer.getName() + "님의 정보수정");
System.out.println("1. 전화번호 수정");
System.out.println("2. 주소 수정");
System.out.println("0. 수정 취소");
System.out.print("메뉴선택 : ");
try {
menu = Integer.parseInt(br.readLine());
} catch(NumberFormatException nfe) {
menu = -1;
}
switch(menu) {
case 1:
System.out.println("수정할 전화번호 = ");
String tel = br.readLine();
myCustomer.setTel(tel);
System.out.println("성공적으로 전화번호를 수정하였습니다.");
isStop = true;
break;
case 2:
System.out.println("수정할 주소 = ");
String address = br.readLine();
myCustomer.setAddress(address);
System.out.println("성공적으로 주소를 수정하였습니다.");
isStop = true;
break;
case 0:
System.out.print("정말로 취소하시겠습니까? (y/n) : ");
String result = br.readLine();
if(result.equals("Y") || result.equals("y")) {
isStop = true;
System.out.println("정보 수정을 취소합니다.");
}
default:
System.err.println();
System.err.println("메뉴선택 오류 : 메뉴를 확인하시고 다시 입력해주세요");
break;
}
System.out.println();
}
}
private void searchCustomer() throws IOException {
System.out.println();
System.out.print("찾으시는 고객 이름 = ");
String name = br.readLine();
position = -1; // 연속으로 고객검색시 문제를 해결하기 위해서
for(int i=0; i<data.size(); i++) {
Customer myCustomer = data.get(i);
if(name.equals(myCustomer.getName())) {
position = i;
break;
}
}
System.out.println();
if(position < 0) {
System.out.println(name + "님은 저의 고객이 아닙니다.");
System.out.println("고객 등록을 먼저 수행하세요.");
}else {
System.out.println(name + "님의 고객정보 검색 성공");
}
}
// 고객정보(이름, 나이, 전화번호, 주소)를 ArrayList에 등록해주는 메서드
private void addCustomer() throws IOException {
System.out.println();
System.out.print("고객 이름 = ");
String name = br.readLine();
System.out.print("나이 = ");
int age = 0; /// try 안에서 선언하면 지역변수가 되기 때문에
try {
age = Integer.parseInt(br.readLine());
} catch(NumberFormatException nfe) {
age = -1; // 고객이 자기 나이를 밝히지 않은 것으로 인식 (대체값 기법)
}
System.out.print("전화번호 = ");
String tel = br.readLine();
System.out.print("주소 = ");
String address = br.readLine();
Customer myCustomer = new Customer(name, age, tel, address);
data.add(myCustomer);
System.out.println("고객정보가 성공적으로 등록되었습니다.");
// 다 받으면 무한 데이터
}
public static void main(String[] args) {
CustomerManager manager = new CustomerManager();
try{
manager.start();
} catch(IOException e) {
e.printStackTrace();
}
}
}
728x90
반응형
'IT&코딩 > Java' 카테고리의 다른 글
Java - 20일차 (Java Network) - X (0) | 2022.11.09 |
---|---|
Java - 19일차 (Thread) - X (0) | 2022.11.09 |
Java - 18일차 (AWT) (0) | 2022.11.09 |
Java - 17일차 (Java IO - File) (0) | 2022.11.03 |
Java - 16일차 (Event) - X (0) | 2022.11.03 |