즐거운프로그래밍

[자바] 직렬화(Serialization)

수수께끼 고양이 2023. 10. 24. 17:20
728x90
반응형

 

참고링크

REAKWON :: [자바] 직렬화(Serialization)의 개념과 객체 파일로 저장하기 예제 - ObjectOutputStream, ObjectInputStream (tistory.com)

 

[자바] 직렬화(Serialization)의 개념과 객체 파일로 저장하기 예제 - ObjectOutputStream, ObjectInputStream

직렬화(Serialization) 우리는 파일에 텍스트를 기록하고, 이진 데이터를 기록하는 방법은 많이들 알고 계시겠습니다. 그런데 만약 이런 종류의 데이터들이 아니라 객체를 파일로 저장하거나 읽어

reakwon.tistory.com

 

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static void main(String[] args) throws IOException,ClassNotFoundException {
        Account wuser = new Account("aaa@ggg.ccc", "AAA", "seoul", "010-1234-1234");

        Account ruser = null;

        FileOutputStream fos = new FileOutputStream("user.acc");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(wuser);

        FileInputStream fis = new FileInputStream("user.acc");
        ObjectInputStream ois = new ObjectInputStream(fis);
        ruser=(Account)ois.readObject();

        System.out.println(ruser);
        System.out.println(ruser.getEmail());
        System.out.println(ruser.getName());
        System.out.println(ruser.getAddress());
        System.out.println(ruser.getPhone());
        System.out.println(ruser.getRegDate());

        oos.close();
        ois.close();
    }
}


class Account implements Serializable {
    private String email;
    private String name;
    private String address;
    private String phone;
    private Date reg_date;
    private transient String password;
    public Account(String email, String name, String address, String phone) {
        this.email=email;
        this.name=name;
        this.address=address;
        this.phone=phone;
        reg_date = new Date();
        password="12342134";
    }
    public String getEmail() {
        return email;
    }
    public String getName() {
        return name;
    }
    public String getAddress() {
        return address;
    }
    public String getPhone() {
        return phone;
    }
    public String getRegDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(reg_date);
    }
    public String toString() {
        return "Information: "+getEmail()+"/"+getName()+"/"+getAddress()+"/"+getPhone()+"/"+getRegDate();
    }
}

// https://reakwon.tistory.com/160

 

 

728x90
반응형