자바 직렬 화 와 반 직렬 화 간단 한 인 스 턴 스

2413 단어
User. java 실체 클래스: package com. ctgu. testSerializable;
import java.io.Serializable;
public class User implements Serializable{
/**
 *    
 */
private static final long serialVersionUID = 1L;

private String name;

private String pwd;

private int age;

public User(String name, String pwd, int age) {
    this.name = name;
    this.pwd = pwd;
    this.age = age;
}

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getPwd() {
    return pwd;
}
public void setPwd(String pwd) {
    this.pwd = pwd;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
@Override
public String toString() {
    return "User [name=" + name + ", pwd=" + pwd + ", age=" + age + "]";
}

}
TestSerializable. java 테스트 클래스: package com. ctgu. testSerializable;
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream;
public class TestSerializable{
User user = new User("  ", "123", 22);

ObjectOutputStream oos = null;  

ObjectInputStream ois = null;

File file = new File("C:/Users/Administrator/Desktop/user.txt");
/**
 *    
 */
public void doSerializable(){
    try {
        oos = new ObjectOutputStream(new FileOutputStream(file));
        oos.writeObject(user);
        oos.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 *     
 */
public void noSerializable(){
    try {
        ois = new ObjectInputStream(new FileInputStream(file));
        User user2 = (User)ois.readObject();
        System.out.println(user2.toString());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        try {
            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public static void main(String[] args) {
    TestSerializable ts = new TestSerializable();
    ts.doSerializable();
    ts.noSerializable();
}

} 실행 결과: User [name = 큰 털, pwd = 123, age = 22]

좋은 웹페이지 즐겨찾기