将java对象序列化到本地

package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Snippet {
     public static void main(String[] args) throws Exception {  
            File file = new File("D://person.out");
            ObjectOutputStream oout = new ObjectOutputStream(new FileOutputStream(file));  
            Person person = new Person(101, "John");
            oout.writeObject(person);
            oout.close();  
    
            ObjectInputStream oin = new ObjectInputStream(new FileInputStream(file));  
            Person newPerson = (Person) oin.readObject(); // 强制转换到Person类型  
            oin.close();  
            System.out.println(newPerson.getColor()+newPerson.getNum());
        }  

}



被序列化对象类   该类必须实现serializable 接口

package test;

import java.io.Serializable;

public class Person implements Serializable{
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    int num;
    String color;
    public Person(){}
    public Person(int num,String color){
        this.num = num;
        this.color = color;
    }
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    
}


你可能感兴趣的:(将java对象序列化到本地)