java-序列化

package test;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class testxulh implements Serializable
{
    private static final long serialVersionUID = 1L;
    private String name="SheepMu";
    private static int age=24;
    
    public final String getName() {
return name;
}
public final void setName(String name) {
this.name = name;
}
public static final int getAge() {
return age;
}
public static final void setAge(int age) {
testxulh.age = age;
}
public static void main(String[] args)
    {//以下代码实现序列化
        try
        {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("my.out"));//输出流保存的文件名为 my.out ;ObjectOutputStream能把Object输出成Byte流
            testxulh testxulh=new testxulh();
            testxulh.setName("狗剩");
            testxulh.setAge(100);
            oos.writeObject(testxulh); 
            oos.flush();  //缓冲流 
            oos.close(); //关闭流
        } catch (FileNotFoundException e) 
        {        
            e.printStackTrace();
        } catch (IOException e) 
        {
            e.printStackTrace();
       
        fan();//调用下面的  反序列化  代码
    }
    public static void fan()    {
       
          
        ObjectInputStream oin = null;//局部变量必须要初始化
        try
        {
            oin = new ObjectInputStream(new FileInputStream("my.out"));
        } catch (FileNotFoundException e1)
        {        
            e1.printStackTrace();
        } catch (IOException e1)
        {
            e1.printStackTrace();
        }      
        testxulh mts = null;
        try {
            mts = (testxulh ) oin.readObject();//由Object对象向下转型为testxulh对象
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }     
         System.out.println("name="+mts.name);    
         System.out.println("age="+mts.age);    
    }
}
原文地址:https://www.cnblogs.com/luckForever/p/7254127.html