Java对象串行化实例
2009-10-25 20:53:52 来源:WEB开发网1.StudentList.java:
/**
*
* @author lucifer
*/
package JavaSerializable;
import java.util.*;
import java.io.*;
public class StudentList implements Serializable{
Vector list = new Vector(6);
public StudentList(){}
public void addStudent(String name){
if(name != null)
list.addElement(name);
}
public void listStudent(){
for(int i = 0;i < list.size();i++){
System.out.PRintln("Student" + i + ":" + (String)list.elementAt( i ) + "<br>");
}
}
}
2.StudentListapplication.java:
/**
*
* @author lucifer
*/
package JavaSerializable;
import java.io.*;
public class StudentListApplication {
public StudentListApplication(){}
public void buildStudentList(StudentList list){
list.addStudent("Bob Robinson");
list.addStudent("Steve Robinson");
list.addStudent("Rob Stevinson");
list.addStudent("Tod Thomson");
list.addStudent("Jack Jones");
list.addStudent("Micheal Jackson");
}
public void putStudentList(StudentList list){
try{
ObjectOutputStream os =
new ObjectOutputStream(new FileOutputStream("student.dat"));
os.writeObject( list );
os.flush();
os.close();
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
public StudentList getStudentList(){
StudentList list = null;
try{
ObjectInputStream is = new ObjectInputStream(new FileInputStream("student.dat"));
list = (StudentList)is.readObject();
is.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
if(list != null)
return list;
else
return null;
}
public void invoke(){
StudentList list = new StudentList();
buildStudentList(list);
System.out.println("Before Serializable:<br>");
list.listStudent();
putStudentList(list);
System.out.println("After Serializable:<br>");
StudentList inlist = getStudentList();
if(inlist != null)
inlist.listStudent();
else
System.out.println("Read Failed!");
try{
System.out.println("Press enter to quit");
System.in.read();
}
catch(Exception e){
System.err.println(e.getMessage());
}
}
public static void main(String[] args){
StudentListApplication sla = new StudentListApplication();
sla.invoke();
}
}
更多精彩
赞助商链接