• 对象序列化工具类


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

     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 }
  • 相关阅读:
    stringstream用法
    来到上海了
    [转]强悍!情书居然能写得如此专业
    asp.net控件开发基础(23)
    当你遇到internal的时候
    asp.net控件设计时支持(3)
    asp.net控件设计时支持(5)
    CS中的缓存类,保证都看的懂
    快要毕业了
    asp.net控件设计时支持(4)
  • 原文地址:https://www.cnblogs.com/godlei/p/5582158.html
Copyright © 2020-2023  润新知