WEB开发网
开发学院WEB开发Jsp Java对象串行化实例 阅读

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{

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();
   }

}

Tags:Java 对象 串行

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接