본문으로 바로가기

궁금한 사항은 댓글로 남겨주세요. 소스마다 주석을 남겼으니 참고하시면 됩니다.

    1. 개인정보를 입력을 통해 받는다(고유번호, 이름, /집 전화번호, 성별, 나이, 메일)
    2. 리스트화 하는 출력기능
    3. 고유번호를 통해 수정/삭제 기능 추가
    4. 저장된 개인정보를 파일에 저장하는 기능 추가
    5. 저장된 파일을 불러오는 기능 추가

 

개발 요점

  - 개인정보를 저장하는 PersonInfo 객체

  - 입력, 수정, 삭제 역할을 담당하는 객체 생성

  - 고정배열 보다는 그때그때 추가를 위하여 List 객체로 관리한다.

  - 파일 저장 및 불러오기를 담당하는 객체 생성

 

FileUtil.java(파일 입출력 객체)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
 
 
 
public class FileUtil {
 
     /**
     * @param file 개인정보가 저장된 파일
     * @return List<PersonInfo>
     */
    public static List<PersonInfo> readFile(File file) throws IOException {
        FileReader filereader = null;
        List<PersonInfo> InfoList = new ArrayList<PersonInfo>();
 
        try {
            filereader = new FileReader(file);
            //파일에서 읽어온 정보를 List에 저장한다.
            InfoList = readReader(filereader);
        } finally {
            if (filereader != null)
                filereader.close();
        }
        return InfoList;
    }
    
    /**
     * 
     * @param dir 저장할 디렉토리
     * @param name 파일명
     * @param InfoList 개인정보가 저장된 List
     * @throws IOException
     * 
     */
    public static void writeFile(String dir, String name, List<PersonInfo> InfoList ) throws IOException {
        OutputStream out = null;
        try {
            File dirent = new File(dir);
            
            //저장할 디렉토리가 존재하지 않으면 생성
            if(!dirent.exists()) {
                dirent.mkdir();
            }
 
            File outFile = new File(dir, name);
 
            //파일이 존재한다면 삭제한다.
            if(outFile.exists()) {
                outFile.delete();
            }
 
            //파일에 String값을 입력할 BufferedOutputStream 생성
            out = new BufferedOutputStream(new FileOutputStream(outFile));
            for(int idx=0; idx < InfoList.size(); idx++) {
                //List에서 개인정보를 가져온다.
                String writeStr = InfoList.get(idx).getPN() + "," + InfoList.get(idx).getName() + "," + InfoList.get(idx).getAge() + ","
                                + InfoList.get(idx).getSex() + ","+ InfoList.get(idx).getNumber() + "," + InfoList.get(idx).getPhonenumber()+"\n";
 
                //저장한 string값을 Byte 배열로 변경
                byte[] b = writeStr.getBytes();
                
                //파일에 해당 내용을 쓴다.
                out.write(b);
            }
        } catch (IOException ioe) {
            //입출력에서 예외발생시 예외 내용 출력
            ioe.printStackTrace();
            throw ioe;
        } finally {
            try {
                //BufferdOutputStream 객체를 close해준다.
                if (out != nullout.close();
            } catch (Exception e) {
            }
        }
    } 
    
    /**
     * 
     * @param input
     * @return
     * @throws IOException
     */
    public static List<PersonInfo> readReader(Reader input) throws IOException {
        try {
            //파일의 내용을 읽어들일 BufferReader 객체 생성
            BufferedReader in = new BufferedReader(input);
            String line;
            
            List<PersonInfo> InfoList = new ArrayList<PersonInfo>();
 
            //파일을 한줄씩 읽어간다. 
            while((line=in.readLine()) != null) {
                // ","로 split하여 배열에 저장
                String[] writeStr = line.split(",");
                
                // 모든 정보가 저장되어 있지 않다면 skip한다.
                if(writeStr.length != 6continue;
                
                PersonInfo personInfo = new PersonInfo();
                
                //각 개인정보를 저장한다.
                personInfo.setPN(Integer.parseInt(writeStr[0]));
                personInfo.setName(writeStr[1]);
                personInfo.setAge(Integer.parseInt(writeStr[2]));
                personInfo.setSex(writeStr[3]);
                personInfo.setNumber(writeStr[4]);
                personInfo.setPhonenumber(writeStr[5]);
                
                //리스트에 객체 추가.
                InfoList.add(personInfo);
            }
            
            return InfoList;
        } finally {
            input.close();
        }
    }
}
 
 
 

 

PersonInfo.java(개인정보 객체)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
 
public class PersonInfo {
    //고유번호
    private int PN;
    //이름
    private String name;
    
    //나이
    private int age;
    
    //성별
    private String sex;
    
    //집전화
    private String number;
    
    //휴대폰번호
    private String phonenumber;
 
    /*
     * 각 멤버 변수 별 SET/GET Method
     */
    public int getPN() {
        return PN;
    }
 
    public void setPN(int pn) {
        this.PN = pn;
    }
    
    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 getSex() {
        return sex;
    }
 
    public void setSex(String sex) {
        this.sex = sex;
    }
 
    public String getNumber() {
        return number;
    }
 
    public void setNumber(String number) {
        this.number = number;
    }
 
    public String getPhonenumber() {
        return phonenumber;
    }
 
    public void setPhonenumber(String phonenumber) {
        this.phonenumber = phonenumber;
    }
    
    public void showInfo() {
        System.out.println("이름 : " + this.name);
        System.out.println("나이 : " + this.age);
        System.out.println("성별 : " + this.sex);
        System.out.println("전화번호 : " + this.number);
        System.out.println("휴대폰번호 : " + this.phonenumber);
    }
}
 
 

 

PersonManager.java(개인정보 저장/삭제/수정)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
 
 
public class PersonManager {
    //개인정보 저장할 List
    private List<PersonInfo> InfoList = new ArrayList<PersonInfo>(); 
    //개인별 고유번호 
    private int PN = 0;
 
    /**
     * 
     * @return
     */
    public List<PersonInfo> getInfoList(){
        return this.InfoList;
    }
    
    /**
     * 
     * @param InfoList
     */
    public void setInfoList(List<PersonInfo> InfoList) {
        this.InfoList = InfoList;
    }
 
    /**
     * @param personInfo
     * @return
     */
    public int addInfo(PersonInfo personInfo) {
        //성공여부 return 변수
        int ret = 0;
 
        try {
            //교유번호 지정
            personInfo.setPN(++this.PN);
            
            //List에 객체를 추가 해 준다.
            this.InfoList.add(personInfo);
            
        }catch(Exception e) {
            System.out.println("정보 추가 중 에러가 발생하였습니다." + "\n" + e.getMessage());
            //return값 변경(0 : 정상, 1 : 에러) 
            ret = 1;
        }
        
        return ret;
    }
    
    /**
     * @param PN
     * @return
     */
    public int removeInfo(int PN) {
        //성공여부 return 변수
        int ret = 0;
        
        try {
            //List개수만큼 for문
            for(int idx=0; idx < this.InfoList.size(); idx++) {
                PersonInfo tempPersonInfo = this.InfoList.get(idx);
 
                if(PN == tempPersonInfo.getPN()) {
                    //고유번호를 비교하여 같은 번호의 정보를 삭제한다.
                    this.InfoList.remove(idx);
                    break;
                }
                
                if(idx == this.InfoList.size()-1) {
                    ret = 2;
                }
            }
        }catch(Exception e) {
            System.out.println("정보 삭제 중 에러가 발생하였습니다." + "\n" + e.getMessage());
            //return값 변경(0 : 정상, 1 : 에러, 2 : 해당정보없음) 
            ret = 1;
        }
        
        return ret;
    }
    
    /**
     * @param PN
     * @param personInfo
     * @return
     */
    public int updateInfo(PersonInfo personInfo, int PN) {
        //성공여부 return 변수
        int ret = 0;
        
        try {
            //List개수만큼 for문
            for(int idx=0; idx < this.InfoList.size(); idx++) {
                PersonInfo tempPersonInfo = this.InfoList.get(idx);
 
                if(PN == tempPersonInfo.getPN()) {
                    personInfo.setPN(PN);
 
                    //고유번호를 비교하여 같은 번호의 정보를 수정한다.
                    this.InfoList.remove(idx);
                    this.InfoList.add(idx, personInfo);
                    break;
                }
                
                if(idx == this.InfoList.size()-1) {
                    ret = 2;
                }
            }
        }catch(Exception e) {
            System.out.println("정보 수정 중 에러가 발생하였습니다." + "\n" + e.getMessage());
            //return값 변경(0 : 정상, 1 : 에러, 2 : 해당정보없음) 
            ret = 1;
        }
        
        return ret;
    }
    
    
    public void showInfo() {
        for(int idx=0; idx < this.InfoList.size(); idx++) {
            System.out.println("##########################");
            System.out.println("고유번호 : " + this.InfoList.get(idx).getPN()
                                +"\n이름 : " + this.InfoList.get(idx).getName()
                                +"\n나이 : " + this.InfoList.get(idx).getAge()
                                +"\n성별 : " + this.InfoList.get(idx).getSex()
                                +"\n전화번호 : " + this.InfoList.get(idx).getNumber()
                                +"\n휴대폰번호 : " + this.InfoList.get(idx).getPhonenumber()
                                );
            System.out.println("##########################");
        }
    }
}
 
 

 

PersonDesk.java(메인클래스)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
 
import java.util.Scanner;
 
 
public class PersonDesk {
    private static Scanner scan = new Scanner(System.in);
    public static void main(String[] args) throws IOException {
        //추가, 삭제, 수정을 위한 객체 생성
        PersonManager pm = new PersonManager();
        
        //저장할 위치 및 파일
        String filepath = "c:\\test\\";
        String filename = "person.txt";
 
        boolean power = true;
        
        while(power) {
            scan.reset();
            System.out.println("1. 출력, 2. 추가, 3. 수정, 4. 삭제, 5. 파일저장, 6. 파일에서불러오기, 7. 종료, 8. 처음으로");
            
            String menuNum = scan.next();
 
            if("1".equals(menuNum)) {
                pm.showInfo();
            }else if("2".equals(menuNum)) {
                pm.addInfo(makeInfo());
            }else if("3".equals(menuNum)) {
                System.out.println("수정할 정보의 고유번호를 입력해 주세요.");
                int PN = scan.nextInt();
                pm.updateInfo(makeInfo(), PN);
            }else if("4".equals(menuNum)) {
                System.out.println("삭제할 정보의 고유번호를 입력해 주세요.");
                pm.removeInfo(scan.nextInt());
            }else if("5".equals(menuNum)) {
                FileUtil.writeFile(filepath, filename, pm.getInfoList());
            }else if("6".equals(menuNum)) {
                pm.setInfoList(FileUtil.readFile(new File(filepath, filename)));
            }else if("7".equals(menuNum)) {
                power = false;
            }else if("8".equals(menuNum)) {
                continue;
            }else {
                System.out.println("해당 메뉴는 없는 메뉴입니다. 다시 선택 바랍니다.");
                continue;    
            }
        }
        scan.close();
    }
    
    public static PersonInfo makeInfo() {
        scan.reset();
        PersonInfo person = new PersonInfo();
        
        System.out.print("이름 : ");
        person.setName(scan.next());
        
        System.out.println();
 
        System.out.print("나이 : ");
 
        System.out.println();
 
        System.out.print("성별  : ");
 
        System.out.println();
 
        System.out.print("전화번호  : ");
        person.setNumber(scan.next());
 
        System.out.println();
 
        System.out.print("휴대폰번호  : ");
        person.setPhonenumber(scan.next());
        
        System.out.println();    
        
        return person;
    }
}
 
 

 

 

결 과