Implementation of io stream serialization in express e stack

Posted by CantonWeb on Wed, 09 Mar 2022 16:25:17 +0100

Express e stack (Io serialization)

MVC mode (three-tier architecture mode)

Concept:

MVC (model view controller) is a framework mode. In the classic MVC mode, M refers to the business model, V refers to the user interface, and C refers to the controller.

M: Namely model A model is a model that represents business rules.
V: Namely View View refers to the interface that users see and interact with.
C: Namely controller Controller means that the controller accepts the user's input and calls the model and view to complete the user's requirements.

Title:

It's still familiar with the taste and the same formula. We can iterate on the basis of the previous one and permanently save the express information to disk in the form of IO stream. Note that multiple objects are saved here, so it's recommended to use serialization and deserialization technology to realize data storage.

Serialization code:

The first time I used serialization, I was a little dizzy. I almost adjusted it in the middle. I didn't adjust it myself. Ha ha. No more gossip. Let's see how I can achieve it

Serialization tool class:

package cn.sunzihan.java.utils;

import cn.sunzihan.java.bean.Express;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sunzihan
 * Serialization and deserialization tool classes
 */
public class ObjectUtils {
    /**
     * serialize
     */
    static File fileName = new File("a.txt");

    public static File returnFile() {
        return fileName;
    }

    public static void outputStream(HashMap<String, Express> map) throws IOException {
        List<Express> list = new ArrayList<>();
        FileOutputStream fouts = new FileOutputStream(fileName);
        ObjectOutputStream out = new ObjectOutputStream(fouts);
        for (Map.Entry<String, Express> stringExpressEntry : map.entrySet()) {
            list.add(stringExpressEntry.getValue());
        }
        out.writeObject(list);
        out.flush();
        out.close();
        fouts.close();
    }

    /**
     * Deserialization
     */
    public static ArrayList<Express> inputStream() throws IOException, ClassNotFoundException {
        if (!fileName.exists()) {
            boolean newFile = fileName.createNewFile();
            return new ArrayList<Express>();
        }
        FileInputStream fis = new FileInputStream(fileName);
        ObjectInputStream ois = new ObjectInputStream(fis);
        return (ArrayList<Express>) ois.readObject();

    }

}

Serialization (saving information) implementation:

My idea is that every time I print all express messages, I serialize IO once to update the file data

 /**
     * Query all express
     */
    public void printAll(HashMap<String, Express> map) {
        for (Map.Entry mapEntry:map.entrySet()) {
            System.out.println(mapEntry.getValue());
        }
        try {
            ObjectUtils.outputStream(map);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

Deserialization (read file) implementation:

Through the static code block, the file is read every time the ExpressDao class is loaded. ps: the static code block is read only once when the class is loaded

    /**
     * Deserialization using static code blocks
     */
    static {
        //Judge whether the content in the file is empty. If there is no content, it will not be executed
        if (ObjectUtils.returnFile().length() !=0) {
            try {
                ArrayList<Express> expresses = ObjectUtils.inputStream();
                for (Express e:expresses) {
                    map1.put(e.getNumber(),e);
                    map2.put(e.getCode(),e);
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

Code implementation:

1,cn.suzihan.java.view package

Included classes: the View class is used for user interaction

package cn.sunzihan.java.view;

import cn.sunzihan.java.bean.Express;
import cn.sunzihan.java.utils.ObjectUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * @author sunzihan
 */
public class View {
    Scanner input = new Scanner(System.in);

    /**
     * welcome
     */
    public void welcome() {
        System.out.println("Welcome to express e Stack");
    }

    /**
     * bye
     */
    public void bye() {
        System.out.println("Look forward to your next use!!");
    }

    /**
     * opening menu
     */
    public int menu() {
        System.out.println("Please follow the prompts");
        System.out.println("Please select your identity: 1-Courier 2-User 0-sign out");
        String s = input.nextLine();
        int num = -1;
        try {
            num = Integer.parseInt(s);
        } catch (NumberFormatException e) {

        }
        if (num < 0 || num > 2) {
            System.out.println("Your input is incorrect, please re-enter");
            return menu();
        }
        return num;
    }

    /**
     * Courier menu
     */
    public int courierMenu() {
        System.out.println("Please follow the instructions");
        System.out.println("Please enter the function to operate:");
        System.out.println("1-Enter Express");
        System.out.println("2-Modify Express");
        System.out.println("3-Delete Express");
        System.out.println("4-Query all express");
        System.out.println("0-Return to the previous level");
        String s = input.nextLine();
        int num = -1;
        try {
            num = Integer.parseInt(s);
        } catch (NumberFormatException e) {

        }
        if (num < 0 || num > 4) {
            System.out.println("Your input is incorrect, please re-enter");
            return courierMenu();
        }
        return num;
    }

    /**
     * User menu
     */
    public String userMenu() {
        System.out.println("Please follow the prompts");
        System.out.println("Please enter the 6-digit pick-up Code:");
        String code = input.nextLine();
        int num = -1;
        try {
            num = Integer.parseInt(code);
        } catch (NumberFormatException e) {

        }
        if (num < 100000 || num > 999999) {
            System.out.println("Your input is incorrect, please re-enter!");
            return userMenu();
        }
        return code;
    }

    /**
     * Express entry
     */
    public Express add() {
        System.out.println("Please follow the prompts");
        System.out.println("Please enter the courier number:");
        String number = input.nextLine();
        System.out.println("Please enter the courier company:");
        String company = input.nextLine();
        Express express = new Express();
        express.setNumber(number);
        express.setCompany(company);
        return express;
    }

    /**
     * Check number
     */
    public String exitNumber() {
        System.out.println("Follow the prompts:");
        System.out.println("Please enter to modify/Deleted doc No.:");
        return input.nextLine();
    }

    /**
     * Modify Express
     */
    public Express update() {
        System.out.println("Please enter a new courier number:");
        String newNumber = input.nextLine();
        System.out.println("Please enter a new express company:");
        String company = input.nextLine();
        Express express = new Express();
        express.setCompany(company);
        express.setNumber(newNumber);
        return express;
    }

    public String delete() {
        System.out.println("Select Delete or not: 1-Yes 2-no");
        String nextLine = input.nextLine();
        int num = -1;
        try {
            num = Integer.parseInt(nextLine);
        } catch (NumberFormatException e) {

        }
        if (num < 1 || num > 2) {
            System.out.println("Your input is incorrect, please re-enter");
            return delete();
        }
        return nextLine;

    }

    /**
     * Successful information printing
     */
    public void success(int num) {
        if (num == 1) {
            System.out.println("Added successfully!!");
        } else if (num == 2) {
            System.out.println("Modified successfully");
        } else if (num == 3) {
            System.out.println("Deleted successfully");
        } else if (num == 4) {
            System.out.println("Pick up successfully. Welcome to pick up next time");
        }
    }

    /**
     * Failure information printing
     */
    public void fail(int num) {
        if (num == 1) {
            System.out.println("The order No. already exists, please re-enter!");
        } else if (num == 2) {
            System.out.println("The number you entered does not exist, please re-enter!");
        } else if (num == 3) {
            System.out.println("Cancel deletion. Returning....");
        } else if (num == 4) {
            System.out.println("The pickup code you entered does not exist, please re-enter!");
        }else if (num==5){
            System.out.println("There is no express in the express cabinet!!");
        }
    }


    /**
     * Query all express
     */
    public void printAll(HashMap<String, Express> map) {
        for (Map.Entry mapEntry:map.entrySet()) {
            System.out.println(mapEntry.getValue());
        }
        try {
            ObjectUtils.outputStream(map);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}

2,cn.suzihan.java.bean package

Included classes: Express class describes Express objects, including various properties and methods of Express objects

package cn.sunzihan.java.bean;

import java.io.Serializable;
import java.util.Objects;

/**
 * @author sunzihan
 */
public class Express implements Serializable {
    private static final long serialVersionUID = -3480760401332925523L;

    private int position;
    private String number;
    private String company;
    private String code;

    public Express() {

    }

    public Express(int position, String number, String company, String code) {
        this.position = position;
        this.number = number;
        this.company = company;
        this.code = code;
    }

    @Override
    public String toString() {
        return "Express information--" +
                "courier number:" + number +
                ", Courier Services Company:" + company +
                ", Location of express cabinet:" + position +
                ", Pick up code:" + code;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Express express = (Express) o;
        return position == express.position && Objects.equals(number, express.number) && Objects.equals(company, express.company) && Objects.equals(code, express.code);
    }

    @Override
    public int hashCode() {
        return Objects.hash(position, number, company, code);
    }

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}

3,cn.suzihan.java.dao package

Included classes: ExpressDao class is used for data storage and business logic

package cn.sunzihan.java.dao;

import cn.sunzihan.java.bean.Express;
import cn.sunzihan.java.utils.ObjectUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

/**
 * @author sunzihan
 */
public class ExpressDao {
    static HashMap<String, Express> map1 = new HashMap<>();
    static HashMap<String, Express> map2 = new HashMap<>();
    static Random random = new Random();
   static int i =0;
    /**
     * Deserialization using static code blocks
     */
    static {
        //Judge whether the content in the file is empty. If there is no content, it will not be executed
        if (ObjectUtils.returnFile().length() !=0) {
            try {
                ArrayList<Express> expresses = ObjectUtils.inputStream();
                for (Express e:expresses) {
                    map1.put(e.getNumber(),e);
                    map2.put(e.getCode(),e);
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    public static boolean add(Express express) {
        if (map1.containsKey(express.getNumber())) {
            return false;
        }
        //Add random pick-up code
        String codeRandom = codeRandom(express);
        express.setCode(codeRandom);

        //Add express cabinet location
        int positionRandom = positionRandom(express);
        express.setPosition(positionRandom);

        map1.put(express.getNumber(), express);
        map2.put(express.getCode(), express);
        return true;
    }

    /**
     * Randomly generate 6-digit pick-up code
     */
    public static String codeRandom(Express express) {
        while (true) {
            int nums = random.nextInt(900000) + 100000;
            if (express.getCode() == null) {
                return Integer.toString(nums);
            } else if (!map2.containsKey(express.getCode())) {
                return Integer.toString(nums);
            }
        }
    }

    /**
     * Judge whether the express delivery order number exists
     */
    public static boolean existNumber(String number) {
        return map1.containsKey(number);
    }

    /**
     * Judge whether the pick-up code exists
     */
    public static boolean exitCode(String code) {
        return map2.containsKey(code);
    }

    /**
     * Delete express delivery by picking up the delivery code
     */
    public static void deletecode(String code) {
        Express express = map2.get(code);
        map1.remove(express.getNumber());
        map2.remove(code);
    }

    /**
     * Randomly generate the location of express cabinet
     */
    public static int positionRandom(Express express) {
        while (true) {
            int nums = random.nextInt(900000) + 100000;
            if (express.getPosition() == 0) {
                return nums;
            } else if (express.getPosition() != nums) {
                return nums;
            }
        }
    }

    /**
     * Modify Express
     */
    public static void update(Express newExpress, String number) {
        Express oldExpress = map1.get(number);
        oldExpress.setNumber(newExpress.getNumber());
        oldExpress.setCompany(newExpress.getCompany());
        map1.remove(number);
        map1.put(newExpress.getNumber(), oldExpress);
    }

    /**
     * Delete by Doc No
     */
    public static void delete(String number) {
        Express express = map1.get(number);
        map2.remove(express.getCode());
        map1.remove(number);
    }

    /**
     * Query all express
     */

    public static HashMap<String, Express> printAll() {
        return map1;
    }
}

4,cn.suzihan.java.main package

Included classes: Main class, Courier class, User class

Main class

package cn.sunzihan.java.main;

import cn.sunzihan.java.view.View;

/**
 * @author sunzihan
 */
public class Main {
    static View view = new View();

    public static void main(String[] args) {
        view.welcome();

        while (true) {
            int menu = view.menu();
            switch (menu) {
                case 1:
                    Courier.courierMenu();
                    break;
                case 2:
                    User.user();
                    break;
                case 0:
                    view.bye();
                    System.exit(0);
                default:
            }
        }
    }
}

Courier class

package cn.sunzihan.java.main;

import cn.sunzihan.java.bean.Express;
import cn.sunzihan.java.dao.ExpressDao;
import cn.sunzihan.java.view.View;

import java.util.HashMap;

/**
 * @author sunzihan
 */
public class Courier {
    static View view = new View();

    public static void courierMenu() {
        while (true) {
            int i = view.courierMenu();
            switch (i) {
                case 1:
                    add();
                    break;
                case 2:
                    update();
                    break;
                case 3:
                    delete();
                    break;
                case 4:
                    printAll();
                    break;
                case 0:
                    return;
                default:
            }
        }
    }

    /**
     * Add express integration
     */
    public static void add() {
        Express express = view.add();
        boolean add = ExpressDao.add(express);
        if (add) {
           view.success(1);
        } else {
             view.fail(1);
        }

    }

    /**
     * Modify express integration
     */
    public static void update() {
        String exitNumber = view.exitNumber();
        boolean b = ExpressDao.existNumber(exitNumber);
        if (b) {
            Express newExpress = view.update();
            ExpressDao.update(newExpress, exitNumber);
            view.success(2);
        } else {
            view.fail(2);
        }
    }

    /**
     * Delete express integration
     */
    public static void delete() {
        String exitNumber = view.exitNumber();
        boolean b = ExpressDao.existNumber(exitNumber);
        if (b) {
            String delete = view.delete();
            switch (delete) {
                case "1":
                    ExpressDao.delete(exitNumber);
                    view.success(3);
                    break;
                case "2":
                    view.fail(3);
                    return;
                default:
            }
        } else {
            view.fail(2);
        }
    }

    /**
     * Query all express integration
     */
    public static void printAll() {
        HashMap<String, Express> map = ExpressDao.printAll();
        if (map.size()!=0) {
            view.printAll(map);
        }else {
            view.fail(5);
        }
    }

User class

package cn.sunzihan.java.main;

import cn.sunzihan.java.dao.ExpressDao;
import cn.sunzihan.java.view.View;

/**
 * @author sunzihan
 */
public class User {
    public static void user() {
        View view = new View();
        String code = view.userMenu();
        boolean b = ExpressDao.exitCode(code);
        if (b) {
            ExpressDao.deletecode(code);
            view.success(4);
        } else {
            view.fail(4);
        }


    }
}

Unresolved BUG

Because the serialization learned for the first time may not be so perfect in implementation. Although there are no bugs in operation, there are bugs in logic.

My idea also said above that the serialization is only carried out by querying the express information. After modifying or deleting the express every time, it needs to be queried or queried when exiting, otherwise it will lead to the disorder of the express information. So what is the solution? Please give me some advice!!!

Topics: Java Back-end Programmer