序列化的private void readObjectNoData()怎么用?

大家谁能给我举个 private void readObjectNoData() throws ObjectStreamException这个的例子啊? 我自己试了半晌还是没试出来怎么用,不是成功反序列化就是抛出异常. 这个函数是怎么用的? 拜托大家了.

package javaPackage;

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

public class Test implements java.io.Serializable
{
    private String name ;
    private int age ;
    private double a ;
    public Test( String name , int age , double a)
    {
        this.name = name ;
        this.age = age ;
        this.a = a ;
    }
    private void writeObject(ObjectOutputStream out)throws IOException
    {
        System.out.println("writeOject") ;
        out.writeObject(new StringBuffer(name).reverse()) ;
        out.writeInt(age) ;
        out.writeDouble(a);
    }
    private void readObject(ObjectInputStream in) throws IOException , ClassNotFoundException
    {
        System.out.println("readOject") ;
        this.name = ( (StringBuffer)in.readObject() ).reverse().toString() ;
        this.a = in.readDouble() ;
        this.age = in.readInt() ;
    }
    private void readObjectNoData() throws ObjectStreamException
    {
        System.out.println("NoOject") ;
        this.name = "无名氏" ;
        this.age = 0 ;
        this.a = 99.9 ;
    }
    @Override
    public String toString()
    {
        return this.name + "\t" + age +"\t" + a ;
    }
    public static void main(String[] args) 
    {
        File tempfile = new File("./" , "Out.txt") ;
        try
        {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(tempfile)) ;
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(tempfile)) ;
        //)
        //{
            if(!tempfile.exists())
            {
                tempfile.createNewFile() ;
            }
            Test a = new Test("测试" , 56 , 4.5) ;
            oos.writeObject(a) ;
            Test temp = (Test)ois.readObject() ;
            System.out.println(temp) ;
        }
        catch (Exception e)
        {
            e.printStackTrace() ;
        }
    }
}

这个是我没修改前的代码,拜托了

阅读 4.7k
1 个回答

代码运行了一下,发现writeread成员时的顺序不对。
read那里改下:

    private void readObject(ObjectInputStream in) throws IOException , ClassNotFoundException{
        System.out.println("readOject") ;
        this.name = ( (StringBuffer)in.readObject() ).reverse().toString() ;
        this.age = in.readInt() ;//这样就跟write时的顺序一致了        
        this.a = in.readDouble() ;
    }

private void readObjectNoData()删掉也能运行的说。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
101 新手上路
子站问答
访问
宣传栏