jdk6.0从入门到精通-----chapter6--对象序列化

要被序列化的对象要实现serialized接口
package Serializable;

import java.io.Serializable;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;

public class MyObject implements Serializable
{
    private int no=0;
    transient private String name=null;
    
    public MyObject(int no, String name)
    {
    	  this.no=no;
    	  this.name=name;
    }
    
    public void setNo(int no)
    {
        this.no=no;
    }
    
    public int getNo()
    {
        return this.no;
    }
    
    public void setName(String name)
    {
        this.name=name;
    }
    
    public String getName()
    {
        return this.name;
    }
    
    [color=red]private void writeObject(ObjectOutputStream out) throws IOException
    {
    	  out.defaultWriteObject();
    	  out.writeObject(this.name);
    }
    
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
    {
    	  in.defaultReadObject();
    	  this.name=(String) in.readObject()+"...";
    }[/color]}


测试类

package Serializable;

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

public class TestSerializable
{
    public static void main(String[] args) throws IOException, ClassNotFoundException
    {        
        File myObjectFile=new File("myobject");  //在当前项目下新建文件
        
        [color=red]ObjectOutputStream[/color] oos=new ObjectOutputStream(new FileOutputStream(myObjectFile));
        MyObject myObject=new MyObject(0,"Tom");
        oos.writeObject(myObject);
        oos.close();
        
        [color=red]ObjectInputStream [/color]ois=new ObjectInputStream(new FileInputStream(myObjectFile));
        MyObject myObject1=(MyObject) ois.readObject();
        System.out.println("no="+myObject1.getNo()+";name="+myObject1.getName());
        ois.close();
    	    }
}


执行结果;
no=0;name=Tom...
并在项目目录下生成myobject文件
内容乱码???

你可能感兴趣的:(java)