关于对象的序列化问题
建立二个文件测试对像序列化
以下是二个文件的源程序
1. objectWrite.java
/*
* Created on 2005-4-28
*
* TODO 对对象进行序列化,保存到 d:\userinfo.dat
*/
package com.lollard.learn;
import java.io.*;
import java.util.*;
/**
* @author Administrator
*
*/
public class objectWrite {
public static void main(String[] args){
Date today = new Date();
UserInfo ui = new UserInfo("a",123456789,"c",today);
try{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:\\userinfo.dat"));
//System.out.print(ui);
oos.writeObject(ui);
oos.close();
}catch(IOException e){
System.out.println("IO error");
}
}
}
class UserInfo implements Serializable{
String name,password;
int user_no;
Date user_date;
UserInfo(String name,int user_no,String password,Date user_date){
this.name = name;
this.password = password;
this.user_no = user_no;
this.user_date = user_date;
}
void printInfo(){
System.out.println("username:" + this.name);
System.out.println("password:" + this.password);
}
}
2.objectRead.java
/*
* Created on 2005-4-28
*/
package com.lollard.learn;
import java.io.*;
import java.util.*;
/**
* @author Administrator
*
* TODO 读取对像失败
*/
public class objectRead {
public static void main(String[] args){
try{
File nf = new File("D:\\userinfo.dat");
FileInputStream fis = new FileInputStream(nf);
ObjectInputStream in = new ObjectInputStream(fis);
Object UserInfo = in.readObject(); //think in java 中的用法
UserInfo.printInfo();
}catch(IOException e){
System.out.println("IO Error");
}
}
}
说明:使用objectWrite.java生成文件没有问题,我参考think in java 中的例子,想重用对象,但是产生错误,内容如下:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method printInfo() is undefined for the type Object
at com.lollard.learn.objectRead.main(objectRead.java:24)
请各位给看一下是那里出了问题,或者有其它用法也可以提一下,谢谢!