Java對象序列化和反序列化的工具方法


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * Java對象序列化和反序列化的工具方法
 */
public class ObjectSerializable implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * Java對象序列化
     */
    public void putData(String filePath, Object data) throws Exception {
        // 1. 檢查該路徑文件是否存在,不存在則創建
        File file = new File(filePath);
        createFileIfNotExists(file);

        // 2. 創建輸出流,將數據寫入文件
        ObjectOutputStream out = null;
        try {
            // 流創建
            out = new ObjectOutputStream(new FileOutputStream(file));

            // 序列化對象
            out.writeObject(data);
        } finally {
            // 關閉流
            if (null != out) {
                out.close();
            }
        }
    }

    // 如果文件不存在,生成一個新文件
    public void createFileIfNotExists(File file) throws IOException {
        // 如果文件不存在,進行創建
        if (!file.exists()) {
            // 如果父目錄不存在,創建父目錄
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            // 創建一個新的文件
            file.createNewFile();
        }
    }

    /**
     * Java對象反序列化
     */
    public Object getData(String filePath) throws Exception {
        // 如果文件不存在,拋個異常
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        }

        // 創建輸入流,從物件中讀取數據
        ObjectInputStream in = null;
        Object object = null;
        try {
            // 流創建
            in = new ObjectInputStream(new FileInputStream(file));

            // 對象反序列化
            object = in.readObject();
        } finally {
            // 關閉流
            if (null != in) {
                in.close();
            }
        }

        // 返回反序列化后的對象
        return object;
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM