employeetest.java

来自「java 完全探索的随书源码」· Java 代码 · 共 72 行

JAVA
72
字号
import java.io.*;public class EmployeeTest{  // Used to keep from hard-coding the filename in multiple places  public static final String EMPLOYEE_FILE = "employees.dat";  public static void main(String[] args)  {    // Create a few employees    Employee employee1 = new Employee( "Zachary", "Cavaness", 10.25f, 40 );    Employee employee2 = new Employee( "Joshua", "Cavaness", 10.25f, 40 );    Employee employee3 = new Employee( "Tracy", "Cavaness", 21.50f, 40 );    try    {      // Create the File and Object streams to serialize to the file      FileOutputStream out = new FileOutputStream( EmployeeTest.EMPLOYEE_FILE );      ObjectOutputStream objOutStr = new ObjectOutputStream( out );      objOutStr.writeObject( employee1 );      objOutStr.writeObject( employee2 );      objOutStr.writeObject( employee3 );      // close the open resources      objOutStr.close();      out.close();    }    catch( FileNotFoundException ex )    {      System.out.println( "Could not create the employee file" );      System.exit(-1);    }    catch( IOException ex )    {      System.out.println( "Could not serialize the employees" );      System.exit(-1);    }    // Read the employees back in    try    {      Object obj = null;      // Create the file and object streams      FileInputStream in = new FileInputStream( EmployeeTest.EMPLOYEE_FILE );      ObjectInputStream objInStr = new ObjectInputStream( in );      // In this example, we will keep going until the EOFException is      // raised and then we will catch that exception and stop      while( true )      {        obj = objInStr.readObject();        System.out.println( obj );      }    }    catch( EOFException ex )    {      System.out.println( "All records have been read in" );    }    catch( FileNotFoundException ex )    {      System.out.println( "Could not create the employee file" );    }    catch( IOException ex )    {      System.out.println( "Could not serialize the employees" );    }    catch( ClassNotFoundException ex )    {      System.out.println( "Could not find the class definition for serialized class" );    }  }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?