본문 바로가기

카테고리 없음

JAVA 연습문제(국비) : 직렬화 및 역직렬화 기능을 이용한 파일 입출력 구현

반응형

 

직렬화란?

   - 객체를 데이터 스트림으로 만드는 것을 뜻한다.

   - 객체에 저장된 데이터를 스트림에 쓰기 위해 연속적인 데이터로 변환하는 것이다.

   - 객체를 파일로 변환시키려면 반드시 직렬화 과정을 거쳐야 한다.

   - 직렬화 대상 클래스는 반드시 Serializable 인터페이스를 구현해야 한다.

 

역직렬화란?

   - 스트림으로부터 데이터를 읽어서 객체를 만드는 것이다.

   - 역직렬화를 수행하는 메인메소드에서는 반드시 ClassNotFoundException 예외처리를 해줘야 한다.

 

 

문제

학생정보 프로그램을 구현 후

학생정보를 입력 받고 입력받은 학생 정보(객체)를 직렬화 기능을 통해 학번.txt 파일로 생성

역직렬화 기능을 이용하여 학생 정보가 담긴 txt 파일을 객체화 하여 객체 내용 출력하기

 

학생정보 저장 클래스

Student.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
package studentManagementQuiz;
 
import java.io.Serializable;
 
public class Student implements Serializable{
    private int stNum;
    private String name;
    private int kor;
    private int eng;
    private int math;
    private char grade;
    
    public void display() {
        System.out.println("이름 : "+ name);
        System.out.println("국어 : "+ kor);
        System.out.println("영어 : "+ eng);
        System.out.println("수학 : "+ math);
        System.out.println("등급 : "+ grade);
    }
    
    public char yourGrade(int kor, int eng, int math) {
        int avg = (int)((kor+eng+math)/3.0);
        if (avg >= 90) {
            this.grade = 'A';
        } else if (avg <90 && avg >= 80) {
            this.grade = 'B';
        } else if (avg <80 && avg >= 70) {
            this.grade = 'C';
        } else if (avg <70 && avg >= 60) {
            this.grade = 'D';
        } else {
            this.grade = 'F';
        }
        return this.grade;
    }
    
    public int getStNum() {
        return stNum;
    }
    public void setStNum(int stNum) {
        this.stNum = stNum;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getKor() {
        return kor;
    }
    public void setKor(int kor) {
        this.kor = kor;
    }
    public int getEng() {
        return eng;
    }
    public void setEng(int eng) {
        this.eng = eng;
    }
    public int getMath() {
        return math;
    }
    public void setMath(int math) {
        this.math = math;
    }
    public char getGrade() {
        return grade;
    }
    public void setGrade(char grade) {
        this.grade = grade;
    }
    
    
}
 
cs

 

학생 프로그램 Main Class

Main.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
package studentManagementQuiz;
 
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) throws IOException, ClassNotFoundException{
        Scanner input = new Scanner(System.in);
        ArrayList<Student> arr = new ArrayList<>();
        while (true) {
            System.out.println("1. 학생 검색");
            System.out.println("2. 등록");
            System.out.println("3. 종료");
            System.out.print(">>>");
            int select = input.nextInt();
            int stNum = 0;
            String name = null;
            int kor = 0;
            int eng = 0;
            int math = 0;
            char grade = 'F';
            switch (select) {
            case 1:
                System.out.print("찾을 학생 학번 입력 : ");
                int num = input.nextInt();
                boolean flag = true;
                for (int i = 0 ; i < arr.size(); i++) {
                    if (arr.get(i).getStNum() == num) {
                        System.out.println("학번 : "+arr.get(i).getStNum());
                        System.out.println("이름 : "+arr.get(i).getName());
                        System.out.println("국어 : "+arr.get(i).getKor());
                        System.out.println("영어 : "+arr.get(i).getEng());
                        System.out.println("수학 : "+arr.get(i).getMath());
                        System.out.println("등급 : "+arr.get(i).getGrade());
                        flag = false;
                        break;
                    }     
                }
                if (flag) {
                    System.out.println("찾는 학생이 없습니다!!");
                }
                break;
            case 2:
                Student st = new Student();
                loop:
                while (true) {
                    System.out.print("학번 입력 : ");
                    stNum = input.nextInt();
                    for (int i = 0 ; i < arr.size(); i++) {
                        if(arr.get(i).getStNum() == stNum) {
                            System.out.println("중복된 학번입니다.");
                            continue loop;
                        }
                    }
                    break;
                }
                System.out.print("이름 입력 : ");
                name = input.next();
                System.out.print("국어 점수 입력 : ");
                kor = input.nextInt();
                System.out.print("영어 점수 입력 : ");
                eng = input.nextInt();
                System.out.print("수학 점수 입력 : ");
                math = input.nextInt();
                grade = st.yourGrade(kor, eng, math);
                st.setStNum(stNum);
                st.setName(name);
                st.setKor(kor);
                st.setEng(eng);
                st.setMath(math);
                st.setGrade(grade);
                System.out.println("가입 되셨습니다!!!");
                arr.add(st);
 
                File f = new File("d:\\test\\학번."+stNum+".txt");
                FileOutputStream fos = new FileOutputStream(f);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                ObjectOutputStream oos = new ObjectOutputStream(bos);
                oos.writeObject(st);
                oos.close();
                break;
            case 3:
                System.exit(0);
                break;
            default:
                System.out.println("잘못된 입력");
                break;
            }
        }
    }
}
 
cs

역직렬화기능 수행 클래스

DeserializationStudent.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
package studentManagementQuiz;
 
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Scanner;
 
public class DeserializationStudentData {
    public static void main(String[] args) throws IOException, ClassNotFoundException{
        Scanner input = new Scanner(System.in);
        Student st = new Student();
        System.out.print("찾아올 파일 학번 이름 입력 : ");
        int num = input.nextInt();
        File f = new File("d:\\test\\학번."+num+".txt");
        FileInputStream fis = new FileInputStream(f);
        BufferedInputStream bis = new BufferedInputStream(fis);
        ObjectInputStream ois = new ObjectInputStream(bis);
        Object obj = ois.readObject();
        st = (Student)obj;
        ois.close();
        st.display();
    }
}
 
cs

 

 

실행 결과

 

다음과 같이 학번 및 학생 정보를 입력 하면

직렬화 코드에 있는 디렉터리 경로에 학번.txt 파일들이 생성된다.

 

 

역직렬화 기능을 하는 클래스의 메인 메소드를 실행시키면

학번을 입력 받고 그 학번과 일치하는 이름의 txt파일을 불러와 역직렬화를 통해 Student 객체로

변환한 뒤 Student 객체의 display() 메소드를 통해 객체 정보를 한번에 출력시킨다.

반응형