java - 序列化的private void readObjectNoData()怎么用?
迷茫
迷茫 2017-04-17 11:48:25
[Java讨论组]

大家谁能给我举个 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() ;
        }
    }
}

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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(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()删掉也能运行的说。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号