---
# System prepended metadata

title: 序列化与反序列化

---

# 序列化与反序列化

在游戏应用中，经常需要存档各个角色对象的的状态，以便于下次上线时能够恢复上次的状态。Java中使用对象序列化和反序列化来解决这个问题。

## Demo


其中类的结构如下图
![](https://i.imgur.com/QvQ40oa.png)


- User 类
```java=
package Bean;

import java.io.Serializable;

public class User implements Serializable {
    private  String name;
    private String password;

    public String getName() {
        return name;
    }

    public String getPassword() {
        return password;
    }

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

    public void setPassword(String password) {
        this.password = password;
    }
}

```

- FileContller 类
```java=
package stream;

import Bean.User;

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

public class FileController {
    public FileController(){

    }

    /**
     * Output obj to disk, default path is ["./Object/" + fileName]
     * @param obj
     * @param fileName
     * @return the output success or not
     */
    public boolean outputUser(Object obj,String fileName) {
        //LinkedHashSet<User> users = new LinkedHashSet<User>();
        //String fileName = "./temp/user.ser";
        fileName = "./Object/" + fileName;
        try {
            FileOutputStream fileOut = new FileOutputStream(fileName);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(obj);
            out.close();
            fileOut.close();
            System.out.println("Serial data has saved in" + fileName);

        } catch (IOException e) {
            System.out.println(e);
            File file = new File("./Object");
            if (!file.exists()) {
                file.mkdir();
                System.out.println(" so mkdir");
            }
            try{
                FileOutputStream fileOut = new FileOutputStream(fileName);
                ObjectOutputStream out = new ObjectOutputStream(fileOut);
                out.writeObject(obj);
                out.close();
                fileOut.close();
                System.out.println("Serial data has saved in: " + fileName);
                return true;
            }catch (IOException noFile){
                System.out.println("mkdir fail, create file fail.");
                return false;
            }
        }
        return true;
    }

    /**
     * Input obj From disk, default path is ["./Object/" + fileName]
     * @param fileName
     * @return obj or null
     */
    public Object inputUser(String fileName){
        fileName = "./Object/" + fileName;
        Object obj;
        try{
            FileInputStream fileIn = new FileInputStream(fileName);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            obj = (Object) in.readObject();
            in.close();
            fileIn.close();
            return  obj;
        }catch(IOException | ClassNotFoundException e){
            System.out.println(e);
            return null;
        }

    }
}

```

- Main 调用
```java=
import Bean.User;
import stream.FileController;

import java.util.LinkedHashSet;

public class Main {
    public  static void main(String[] args) {
        LinkedHashSet<User> users = new LinkedHashSet<>();
        User a = new User();
        a.setName("zzx");
        a.setPassword("zzx55");
        users.add(a);

        //自定义的文件控制类
        FileController fileCtrl = new FileController();

        //序列化(存档)
        //fileCtrl.outputUser(users,"users.ser");

        //反序列化（读档）
        LinkedHashSet<User> usersGet = (LinkedHashSet<User>) fileCtrl.inputUser("users.ser");
        System.out.println(usersGet.size());
        for(User u:usersGet){
            System.out.println(u.getName());
            System.out.println(u.getPassword());
        }
    }
}

```