Persistent preservation of object flow using very hard-core JAVA serialization

Catalog

background

Objects are everywhere in OOP, and we certainly want a data format to store a collection of these objects for persistence.For example, the set of department objects formed by the Department class, the set of employee objects formed by the employee class, or even the object formed by such a class: there are many departments in the company, and there are many employees in each department. We want to persist such an object as a file.

The concept of object flow

To achieve persistent object preservation, we need to introduce the Java object serialization mechanism, which can output any object to the stream:

/**
*Stream Object
*/
Object object = new Object();
//Create object stream and output to fileObject.dat
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("c:\\object.dat"));
//Write object to file
output.writeObject(object);

ObjectInputStream input = new ObjectInputStream(new FileInputStream("c:\\object.dat"));
object = input.readObject();

Object Flow Instances

Introduce an Organization Chart

Define Classes for Organization Schema Diagram
  • Company: Represents the external presence of the organizational structure; the company is a complete entity composed of departments and staff.
  • Departments: Represents the units of operation in the organizational structure; Departments can be divided into different business units by type.
  • Employee: Represents the smallest unit in the organization structure; employees exist in different business units by position.
/**
 * Save Information with Object Flow--Company Class
 *
 * @author  zhuhuix
 * @date 2020-05-27
 */
 class Company implements Serializable {

    //Company id
    private int id;
    //Corporate name
    private String name;
    //List of company departments
    private List<Department> departments;

    //Default constructor
    Company() {
    }

    //Initialization Constructor
    Company(int id, String name) {
        this.id = id;
        this.name = name;
        this.departments = new ArrayList<>();
    }

    //Additional departments
    public void addDepartment(Department department) {
        this.departments.add(department);
    }

    //Cancellation of Departments
    public void deleteDepartment(Department department) {
        this.departments.remove(department);
    }

    //Location Department
    Department findDepartmentByName(String departmentName) {
        Optional<Department> optional = departments.stream().filter(department ->
                department.getName().equals(departmentName)).findFirst();
        return optional.get();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Department> getDepartments() {
        return departments;
    }

    public void setDepartments(List<Department> departments) {
        this.departments = departments;
    }
}

/**
 * Save Information with Object Flow--Department Class
 *
 * @author  zhuhuix
 * @date 2020-05-27
 */
 class Department  implements Serializable {

    //Department id
    private int id;
    //Department Name
    private String name;
    //Superior departments
    private Integer parentId;
    //Department Staff List
    private List<Employee> employees;
    //Default constructor
    Department(){}
    //Initialization Constructor
    Department(int id,String name,Integer parentId){
        this.id=id;
        this.name=name;
        this.parentId=parentId;
        this.employees = new ArrayList<>();
    }
    //Add staff
    public void addEmployee(Employee employee){
        this.employees.add(employee);
    }
    //Remove staff
    public void deleteEmployee(Employee employee){
        this.employees.remove(employee);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getParentId() {
        return parentId;
    }

    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }

    public List<Employee> getEmployees() {
        return employees;
    }

    public void setEmployees(List<Employee> employees) {
        this.employees = employees;
    }
}

/**
 * Save Information with Object Flow--Staff Class
 *
 * @author  zhuhuix
 * @date 2020-05-27
 */
 class Employee implements Serializable {

    //Employee id
    private int id;
    //Employee Name
    private String name;
    //Employee gender
    private String sex;
    //Employee age
    private int age;
    //Employee position
    private String position;
    //Date of entry
    private Date hireDate;
    //Current salary
    private BigDecimal salary;
    //Default constructor
    Employee(){}
    //Initialization Constructor
    public Employee(int id, String name, String sex, int age, String position, Date hireDate, BigDecimal salary) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.position = position;
        this.hireDate = hireDate;
        this.salary = salary;
    }

    //Promotion, transfer, transfer
    public void setPosition(String position){
        this.position = position;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPosition() {
        return position;
    }

    public Date getHireDate() {
        return hireDate;
    }

    public void setHireDate(Date hireDate) {
        this.hireDate = hireDate;
    }

    public BigDecimal getSalary() {
        return salary;
    }

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

The complete structure of the class

Save object information for organization architecture with object flow

With classes and constructors that complete the initialization of objects, we have the ability to build an entire organizational structure. Next, we build a complete organizational structure for the company:

/**
 1. Save organization architecture information with object flow
 2.  * @author  zhuhuix
 3. @date 2020-05-27
 */
public class ObjectStreamSave {
    //Define a global static variable as the id that controls the organization's architecture
    public static int id = 0;

    public static void main(String[] args) throws IOException {


        //establishment of company
        Company company = new Company(id++, "Internet Co., Ltd.");

        //The company establishes the general manager's Office
        Department manageDept = new Department(id++, "General Manager Office", null);
        company.addDepartment(manageDept);

        //Set up Product Department under General Manager
        Department productDept = new Department(id++, "Product Department", manageDept.getId());
        company.addDepartment(productDept);
        //Set up Group A and Group B under Product Department
        company.addDepartment(new Department(id++, "product A group", productDept.getId()));
        company.addDepartment(new Department(id++, "product B group", productDept.getId()));

        //Set up R&D department under General Manager's Office
        Department developmentDept = new Department(id++, "R&D Department", manageDept.getId());
        company.addDepartment(developmentDept);
        //Set up software and hardware groups under R&D Department
        company.addDepartment(new Department(id++, "Software Group", developmentDept.getId()));
        company.addDepartment(new Department(id++, "Hardware Group", developmentDept.getId()));

        //Set up Marketing Department under General Manager
        Department marketDept = new Department(id++, "Marketing Department", manageDept.getId());
        company.addDepartment(marketDept);
        //Set up Creative Group and Channel Group under Marketing Department
        company.addDepartment(new Department(id++, "Creative Group", marketDept.getId()));
        company.addDepartment(new Department(id++, "Channel Group", marketDept.getId()));

        //Personnel appointment in general manager's Office
        manageDept.addEmployee(new Employee(id++, "Mike", "male", 35, "General manager",
                new Date(), BigDecimal.valueOf(100000)));
        manageDept.addEmployee(new Employee(id++, "Tom", "male", 34, "Vice General Manager",
                new Date(), BigDecimal.valueOf(60000)));

        //R&D Personnel Appointment
        developmentDept.addEmployee(new Employee(id++, "Jack", "male", 30, "Director of R&D",
                new Date(), BigDecimal.valueOf(40000)));
        company.findDepartmentByName("Software Group")
                .addEmployee(new Employee(id++, "Kate", "female", 26, "Group members",
                        new Date(), BigDecimal.valueOf(20000)));
        company.findDepartmentByName("Hardware Group")
                .addEmployee(new Employee(id++, "Will", "male", 24, "Group members",
                        new Date(), BigDecimal.valueOf(20000)));

        //Personnel Appointment for Product Department
        productDept.addEmployee(new Employee(id++, "Jerry", "male", 28, "Product Director",
                new Date(), BigDecimal.valueOf(40000)));
        company.findDepartmentByName("product A group")
                .addEmployee(new Employee(id++, "Merry", "female", 28, "Group members",
                        new Date(), BigDecimal.valueOf(20000)));
        company.findDepartmentByName("product B group")
                .addEmployee(new Employee(id++, "Leo", "male", 27, "Group members",
                        new Date(), BigDecimal.valueOf(20000)));

        //Marketing Personnel Appointment
        marketDept.addEmployee(new Employee(id++, "Rose", "female", 29, "Marketing Director",
                new Date(), BigDecimal.valueOf(40000)));
        company.findDepartmentByName("Creative Group")
                .addEmployee(new Employee(id++, "Amy", "", 25, "Group members",
                        new Date(), BigDecimal.valueOf(20000)));
        company.findDepartmentByName("Channel Group")
                .addEmployee(new Employee(id++, "Tony", "male", 23, "Group members",
                        new Date(), BigDecimal.valueOf(20000)));


        //Traverse company organization structure
        int deptCount = 0;
        int empCount = 0;
        Iterator<Department> deptIterator = company.getDepartments().iterator();
        while (deptIterator.hasNext()) {
            deptCount++;
            Department department = deptIterator.next();
            System.out.println("department:" + department.getName());
            if (department.getEmployees() != null) {
                Iterator<Employee> empIterator = department.getEmployees().iterator();
                while (empIterator.hasNext()) {
                    empCount++;
                    Employee employee = empIterator.next();
                    System.out.print(" personnel:" + employee.getName() + " position:" + employee.getPosition() + ",");
                }
                System.out.println();
            }
        }
        System.out.println("Total number of departments:" + deptCount);
        System.out.println("Total number of employees:" + empCount);

        //Save company organization structure to file through object flow
        ObjectOutputStream companyStream = new ObjectOutputStream(new FileOutputStream("c:\\company.dat"));
        companyStream.writeObject(company);
        companyStream.writeObject(company.getDepartments());
        for (int i = 0; i < company.getDepartments().size(); i++) {
            List<Employee> employees = company.getDepartments().get(i).getEmployees();
            companyStream.writeObject(employees);
        }


    }
}
Core Code
  1. Create a stream of objectsCompany.datfile
  2. Write Company objects to files
  3. Write the Department list collection in the company object to a file
  4. Traverse Department lists and write a collection of employee lists under each department to a file


The resulting files are as follows:

Binary information:

Read files and output with object stream
/**
 * Reading information with object streams
 *
 * @author  zhuhuix
 * @date 2020-05-27
 */
public class ObjectStreamRead {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ObjectInputStream companyStream = new ObjectInputStream(new FileInputStream("c:\\company.dat"));
        if (companyStream!=null){
           Company company=(Company) companyStream.readObject();

            //Traverse company organization structure
            int deptCount = 0;
            int empCount = 0;
            Iterator<Department> deptIterator = company.getDepartments().iterator();
            while (deptIterator.hasNext()) {
                deptCount++;
                Department department = deptIterator.next();
                System.out.println("department:" + department.getName());
                if (department.getEmployees() != null) {
                    Iterator<Employee> empIterator = department.getEmployees().iterator();
                    while (empIterator.hasNext()) {
                        empCount++;
                        Employee employee = empIterator.next();
                        System.out.print(" personnel:" + employee.getName() + " position:" + employee.getPosition() + ",");
                    }
                    System.out.println();
                }
            }
            System.out.println("Total number of departments:" + deptCount);
            System.out.println("Total number of employees:" + empCount);

        }

    }
}

Core Code
  1. Obtain by Object StreamCompany.datfile
  2. Read object information


The output is as follows:

summary

In this article, we use serialization to save collections of objects to disk files and get them as they are stored. We learned the following:

  • ObjectOutputStream (OutputStream out) creates an ObjectOutputStream that allows you to write out objects to the specified OutputStream.
  • Void writeObject (Object obj) writes the specified object to ObjectOutputStream, which stores the class of the specified object, the signature of the class, and the values of all non-static and non-instantaneous fields in the class and its superclass.
  • ObjectInputStream (InputStream in) creates an ObjectInputStream to read object information from the specified InputStream.
  • Object readObject() reads an object from ObjectInputStream.In particular, this method reads back the class of the object, the signature of the class, and the values of all non-static and non-instantaneous fields in the class and its superclass.The deserialization it performs allows multiple object references to be recovered.

Tags: Java

Posted on Wed, 27 May 2020 21:44:55 -0400 by LucidParody