0

以下は、従業員の記録を逆シリアル化する必要があるプログラムです。最初のレコードは逆シリアル化されますが、ユーザーが追加した他のレコードは逆シリアル化されません。

import java.io.*;
import java.util.*;

public class Employee implements Serializable {

    private Object name;
    private Object address;
    private Object ssn;
    private Object eadd;
    private Object number;  

    private void writeObject(ObjectOutputStream os) throws IOException {
        os.defaultWriteObject();
    }

    private void readObject (ObjectInputStream is) throws IOException, ClassNotFoundException {
        is.defaultReadObject();
    }


    public static void addEmployee() {
        try {

            Employee e = new Employee();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
            FileOutputStream fileOut = new FileOutputStream("employee.ser", true);
            ObjectOutputStream out =  new ObjectOutputStream(fileOut);
            System.out.println("Name: ");
            e.name = buffer.readLine();
            System.out.println("Address: ");
            e.address = buffer.readLine();
            System.out.println("SSN: ");
            e.ssn = buffer.readLine();
            System.out.println("Email: ");
            e.eadd = buffer.readLine();
            System.out.println("Number: ");
            e.number = buffer.readLine();

            out.writeObject(e +"#");
            out.close();
            fileOut.close();

        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void deserializeAll() throws ClassNotFoundException {
        Employee e = null;
        try {
            FileInputStream fileIn = new FileInputStream("employee.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            e = (Employee) in.readObject();
            in.close();
            fileIn.close();
            System.out.println("Deserialized Employee...");
            System.out.println("Name: " + e.name);
            System.out.println("Address: " + e.address);
            System.out.println("SSN: " + e.ssn);
            System.out.println("Email: " + e.eadd);
            System.out.println("Number: " + e.number);
        }
        catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        int choice;
        Scanner input = new Scanner (System.in);    

        do {
            System.out.println("[1] Add an employee.");
            System.out.println("[2] Deserialize all.");
            choice = input.nextInt();
            switch (choice) {
                case 1: addEmployee(); break;
                case 2: deserializeAll(); break;
                default: System.exit(0);
            }
        } while (choice != 3);

    }

}

これ#は、レコードごとのデリメータです。

4

1 に答える 1