大家谁能给我举个 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() ;
}
}
}
这个是我没修改前的代码,拜托了
代码运行了一下,发现
write
跟read
成员时的顺序不对。read
那里改下:private void readObjectNoData()
删掉也能运行的说。