• 对象序列化工具类


    这个类中提供了对象序列化与反序列化的方法,在实际的项目中会经常被用到。

     1 import java.io.*;
     2 
     3 public class SerializationUtils {
     4 
     5     //把一个对象序列化
     6     public static byte[] serialize(Object state) {
     7         ObjectOutputStream oos = null;
     8         try {
     9             ByteArrayOutputStream bos = new ByteArrayOutputStream(512);
    10             oos = new ObjectOutputStream(bos);
    11             oos.writeObject(state);
    12             oos.flush();
    13             return bos.toByteArray();
    14         }
    15         catch (IOException e) {
    16             throw new IllegalArgumentException(e);
    17         }
    18         finally {
    19             if (oos != null) {
    20                 try {
    21                     oos.close();
    22                 }
    23                 catch (IOException e) {
    24                     // eat it
    25                 }
    26             }
    27         }
    28     }
    29 
    30     //把一个对象反序列化
    31     public static <T> T deserialize(byte[] byteArray) {
    32         ObjectInputStream oip = null;
    33         try {
    34             oip = new ObjectInputStream(new ByteArrayInputStream(byteArray));
    35             @SuppressWarnings("unchecked")
    36             T result = (T) oip.readObject();
    37             return result;
    38         }
    39         catch (IOException e) {
    40             throw new IllegalArgumentException(e);
    41         }
    42         catch (ClassNotFoundException e) {
    43             throw new IllegalArgumentException(e);
    44         }
    45         finally {
    46             if (oip != null) {
    47                 try {
    48                     oip.close();
    49                 }
    50                 catch (IOException e) {
    51                     // eat it
    52                 }
    53             }
    54         }
    55     }
    56 
    57 }
  • 相关阅读:
    sharepoint部署
    继承实体类出现传值时值不能保留
    面试经历
    sharepoint更换数据库链接
    asp.net c# 打开新页面或页面跳转
    sharepoint中配置工作流
    AD添加组织单位
    常用正则表达式
    删除多级非空目录
    C#实现对Word文件读写
  • 原文地址:https://www.cnblogs.com/godlei/p/5582158.html
Copyright © 2020-2023  润新知