java序列化与反序列化简单实例

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]

你可能感兴趣的:(java序列化与反序列化简单实例)