Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Serialization/Deserialization of objects in Java

  1. Jun 24, 2015 #1
    Ok guys, I am working on a simple serialize/deserialize project. A user interface takes the following input:

    A Department ID (INT), A Department Name (String), and Three Employees (ArrayList) that have a Name, Department, and Salary. Once the Three employees are entered, the Department can be submitted with a button. When the submit button is clicked, the Department information should be displayed in the Text area.

    I am writing the Employee object to the console, and to the text area to show the employee is being created, but when the object is retrieved from the file, I seem to have missed something.

    The data is passed into a department object, saved to a file, retrieved from that file, and displayed in a text area. I seem to be retrieving just a memory reference instead of the actual file. I have included the code as follows:

    IDE: Netbeans 8.0.2
    Language: JAVA

    Employee Class:

    Code (Java):
    /*
    * To change this license header, choose License Headers in Project Properties.
    * To change this template file, choose Tools | Templates
    * and open the template in the editor.
    */

    package SerializeObject;

    import java.io.Serializable;

    /**
    *
    * @author Jonathan
    */

    public class Employee implements Serializable {
      private String Name;
      private String title;
      private String department;
      private double salary;
      // stupid example for transient
      private final transient Thread myThread;

      public Employee(String Name, String title, String department, double salary) {
        this.Name = Name;
        this.title = title;
        this.department = department;
        this.salary = salary;
        this.myThread = new Thread();
      }

      public String getName() {
        return Name;
      }

      public String getTitle(){
          return title;
      }

      public void setTitle(String Title){
          this.title = Title;
      }

      public String getDepartment(){
          return department;
      }

      public void setDepartment(String Department){
          this.department = Department;
      }

      public double getSalary(){
          return salary;
      }

      public void setSalary(double Salary){
          this.salary = Salary;
      }


      @Override
      public String toString() {
        return "Employee [firstName = " + Name  + ", title = " + title + ", department = " + department + ", salary = " + salary + "]";
      }

    }
     
    Department Class:

    Code (Text):
    /*
    * To change this license header, choose License Headers in Project Properties.
    * To change this template file, choose Tools | Templates
    * and open the template in the editor.
    */
    package SerializeObject;

    import java.io.Serializable;
    import java.util.ArrayList;

    /**
    *
    * @author Jonathan
    */
    public class Department implements Serializable {
      private int deptID;
      private String deptName;
      private ArrayList<Employee> empArray;

      public Department(int deptID, String deptName, ArrayList empArray) {
        this.deptID = deptID;
        this.deptName = deptName;
      }

      public int getDeptID() {
        return deptID;
      }

      public void setDeptID(int deptID) {
        this.deptID = deptID;
      }

      public String getDeptName() {
        return deptName;
      }

      public void setDeptName(String deptName) {
        this.deptName = deptName;
      }

      public ArrayList getEmpArray(){
          return empArray;
      }

      public void setArrayList(ArrayList empArray){
          this.empArray = empArray;
      }

    }
     
    Interface class/ Test Class

    Code (Java):
    /*
    * To change this license header, choose License Headers in Project Properties.
    * To change this template file, choose Tools | Templates
    * and open the template in the editor.
    */

    package serializationexample;

    import java.util.ArrayList;
    import SerializeObject.*;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;

    /**
    *
    * @author Jonathan
    */

    public class SerializeInterface extends javax.swing.JFrame {
     
        ArrayList empArray = new ArrayList<>();
     
        /**
         * Creates new form SerializeInterface
         */

        public SerializeInterface() {
            initComponents();
            submitDeptButton.setEnabled(false);
        }

        /**
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
         */

        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                        
        private void initComponents() {

            jInternalFrame1 = new javax.swing.JInternalFrame();
            jScrollPane1 = new javax.swing.JScrollPane();
            displayTA = new javax.swing.JTextArea();
            deptLabel = new javax.swing.JLabel();
            deptTF = new javax.swing.JTextField();
            deptIDLabel = new javax.swing.JLabel();
            deptIDTF = new javax.swing.JTextField();
            jPanel1 = new javax.swing.JPanel();
            empNameLabel = new javax.swing.JLabel();
            empNameTF = new javax.swing.JTextField();
            empNameLabel1 = new javax.swing.JLabel();
            empTitleTF = new javax.swing.JTextField();
            empNameLabel2 = new javax.swing.JLabel();
            empSalaryTF = new javax.swing.JTextField();
            addEmpButton = new javax.swing.JButton();
            jLabel1 = new javax.swing.JLabel();
            submitDeptButton = new javax.swing.JButton();
            exitButton = new javax.swing.JButton();

            jInternalFrame1.setVisible(true);

            javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
            jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
            jInternalFrame1Layout.setHorizontalGroup(
                jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 0, Short.MAX_VALUE)
            );
            jInternalFrame1Layout.setVerticalGroup(
                jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 0, Short.MAX_VALUE)
            );

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Department Interface");

            displayTA.setColumns(20);
            displayTA.setRows(5);
            jScrollPane1.setViewportView(displayTA);

            deptLabel.setText("Department Name");

            deptIDLabel.setText("Department ID");

            jPanel1.setName("Employee"); // NOI18N

            empNameLabel.setText("Employee Name");

            empNameLabel1.setText("Employee Title");

            empNameLabel2.setText("Employee Salary");

            addEmpButton.setText("Add Employee 1");
            addEmpButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    addEmpButtonActionPerformed(evt);
                }
            });

            jLabel1.setText("Employee Data");

            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(empNameLabel)
                        .addComponent(empNameLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(empNameLabel2))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(empTitleTF, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(empNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(empSalaryTF, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(21, 21, 21))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(138, 138, 138)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(addEmpButton)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addGap(3, 3, 3)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(empNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(empNameLabel))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(empNameLabel1)
                        .addComponent(empTitleTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(empNameLabel2)
                        .addComponent(empSalaryTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                    .addComponent(addEmpButton)
                    .addContainerGap())
            );

            submitDeptButton.setText("Submit Department");
            submitDeptButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    submitDeptButtonActionPerformed(evt);
                }
            });

            exitButton.setText("Exit");
            exitButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    exitButtonActionPerformed(evt);
                }
            });

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addGap(31, 31, 31)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(deptIDLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(deptLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 153, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(deptTF, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(deptIDTF, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(29, 29, 29))
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1)
                    .addContainerGap())
                .addGroup(layout.createSequentialGroup()
                    .addGap(24, 24, 24)
                    .addComponent(submitDeptButton)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(exitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(41, 41, 41))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(deptIDLabel)
                        .addComponent(deptIDTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(deptLabel)
                        .addComponent(deptTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(35, 35, 35)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(submitDeptButton)
                        .addComponent(exitButton))
                    .addGap(22, 22, 22)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );

            pack();
        }// </editor-fold>                      

        private void addEmpButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
            // TODO add your handling code here:
            switch (addEmpButton.getText()) {
                case "Add Employee 1":
                    {
                        String empName = empNameTF.getText();
                        String empTitle = empTitleTF.getText();
                        String empDept = deptTF.getText();
                        int empSalary = Integer.parseInt(empSalaryTF.getText());
                        Employee employee = new Employee(empName, empTitle, empDept, empSalary);
                        empArray.add(employee);
                        addEmpButton.setText("Add Employee 2");
                        empNameTF.setText("");
                        empTitleTF.setText("");
                        empSalaryTF.setText("");
                        System.out.println(employee);
                        displayTA.setText(employee + "\n");
                        empNameTF.requestFocus();
                        break;
                    }
                case "Add Employee 2":
                    {
                        String empName = empNameTF.getText();
                        String empTitle = empTitleTF.getText();
                        String empDept = deptTF.getText();
                        int empSalary = Integer.parseInt(empSalaryTF.getText());
                        Employee employee = new Employee(empName, empTitle, empDept, empSalary);
                        empArray.add(employee);
                        addEmpButton.setText("Add Employee 3");
                        empNameTF.setText("");
                        empTitleTF.setText("");
                        empSalaryTF.setText("");
                        System.out.println(employee);
                        displayTA.setText(employee + "\n");
                        empNameTF.requestFocus();
                        break;
                    }
                case "Add Employee 3":
                    {
                        String empName = empNameTF.getText();
                        String empTitle = empTitleTF.getText();
                        String empDept = deptTF.getText();
                        int empSalary = Integer.parseInt(empSalaryTF.getText());
                        Employee employee = new Employee(empName, empTitle, empDept, empSalary);
                        empArray.add(employee);
                        addEmpButton.setEnabled(false);
                        submitDeptButton.setEnabled(true);
                        empNameTF.setText("");
                        empTitleTF.setText("");
                        empSalaryTF.setText("");
                        System.out.println(employee);
                        displayTA.setText(employee + "\n");
                        submitDeptButton.requestFocus();
                        break;
                    }
            }
        }                                          

        private void submitDeptButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              
            // TODO add your handling code here:
        String filename = "C:\\Users\\Jonathan\\Desktop\\NuTech Training\\Department.sav";
        Department d = new Department(Integer.parseInt(deptIDTF.getText()), deptTF.getText(), empArray);
     

        // save the object to file
     
        try {
          FileOutputStream fos = new FileOutputStream(filename);
          ObjectOutputStream out = new ObjectOutputStream(fos);
          out.writeObject(d);
          out.flush();
          out.close();
        } catch (Exception ex) {
          ex.printStackTrace();
        }
        // read the object from file
        // save the object to file
        FileInputStream fis;
        ObjectInputStream in;
        try {
          fis = new FileInputStream(filename);
          in = new ObjectInputStream(fis);
          d = (Department)in.readObject();
          System.out.println(d);
          displayTA.setText(d.toString());
          in.close();
          fis.close();
        } catch (IOException | ClassNotFoundException ex) {
          ex.printStackTrace();
        }
     
    //        for(Object empObject : empArray){
    //        System.out.println(empObject.toString());
    //        displayTA.setText(empObject.toString());
    //        }
        }                                              

        private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
            // TODO add your handling code here:
            System.exit(0);
        }                                        

        /**
         * @param args the command line arguments
         */

        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
             */

            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(SerializeInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(SerializeInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(SerializeInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(SerializeInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>

            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new SerializeInterface().setVisible(true);
                }
            });
        }

        // Variables declaration - do not modify                  
        private javax.swing.JButton addEmpButton;
        private javax.swing.JLabel deptIDLabel;
        private javax.swing.JTextField deptIDTF;
        private javax.swing.JLabel deptLabel;
        private javax.swing.JTextField deptTF;
        private javax.swing.JTextArea displayTA;
        private javax.swing.JLabel empNameLabel;
        private javax.swing.JLabel empNameLabel1;
        private javax.swing.JLabel empNameLabel2;
        private javax.swing.JTextField empNameTF;
        private javax.swing.JTextField empSalaryTF;
        private javax.swing.JTextField empTitleTF;
        private javax.swing.JButton exitButton;
        private javax.swing.JInternalFrame jInternalFrame1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JButton submitDeptButton;
        // End of variables declaration                
    }
     
    Actual Output: SerializeObject.Department@4e2acbe3
    Desired Output:
    Employee [firstName = James, title = Dev, department = iOS Dev, salary = 234234.0]
    Employee [firstName = Steve, title = Dev, department = iOS Dev, salary = 23423.0]
    Employee [firstName = Jon, title = Dev, department = iOS Dev, salary = 34234.0]
     
  2. jcsd
  3. Jun 24, 2015 #2
    Your current program does what you ask it to do

    Code (Text):
    try

    fis = new FileInputStream(filename);
          in = new ObjectInputStream(fis);
          d = (Department)in.readObject();
          System.out.println(d);
          displayTA.setText(d.toString());
          in.close();
          fis.close();
    //...
     
    Try to access and print out values returned from public methods in Department class using d before the line System.out.println().
     
  4. Jun 24, 2015 #3

    Borg

    User Avatar
    Science Advisor
    Gold Member

    I can't get it to run because of all of the netbeans dependancies. Adding IDE-specific dependancies is not a good practice.

    The switch in the addEmpButtonActionPerformed() method is really odd. It looks like you don't enable the ability to create the department until three employees have been added. You really need to separate the processing of employees and departments away from the Java Swing components and events. Get the basics of creating and saving data working in smaller examples without all of the Swing clutter. It will be a lot easier to debug then.
     
  5. Jun 24, 2015 #4

    Thanks Silicon, that was the key. I took this advice:
    and swapped out the displayTA and System.out lines. I then modded the displayTA line as follows, and now get the desired output!

    Thanks Again!!!

    Code (Java):
    displayTA.setText("Department ID: = " + d.getDeptID() + "\n" + "Department Name = " + d.getDeptName() + "\n" + "Department Employees = " + d.getEmpArray().toString());
          System.out.println("Department ID: = " + d.getDeptID() + "\n" + "Department Name = " + d.getDeptName() + "\n" + "Department Employees = " + d.getEmpArray().toString());
               
    Now just to print out each element of the array on it's own line and it will be perfect! Thanks again, back to the research/coding!
     
  6. Jun 24, 2015 #5
    This was done by design. Part of the requirement was to not allow creation of a department until 3 employees had been added. I agree that the debugging would be simpler, but reqs have to be met. As for the dependencies, I was in a rush and didn't take the time to remove the ide specific dependencies. I will pay closer attention in the future.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Serialization/Deserialization of objects in Java
Loading...