大家谁能给我举个 private void readObjectNoData() throws ObjectStreamException这个的例子啊? 我自己试了半晌还是没试出来怎么用,不是成功反序列化就是抛出异常. 这个函数是怎么用的? 拜托大家了.
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() ;
}
}
}
这个是我没修改前的代码,拜托了
代码运行了一下,发现write跟read成员时的顺序不对。
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()删掉也能运行的说。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。