📄 employeetest.java
字号:
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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -