zoukankan      html  css  js  c++  java
  • 【转载】java对象和byte数组互转,直接拿去用

    //加了了Optional防止空指针异常,加入了泛型,省去了强制转化
     1 import java.io.*;
     2 import java.util.Optional;
     3 
     4 /**
     5  * Created by Jason on 2017/1/3.
     6  */
     7 public class ByteArrayUtils {
     8 
     9     public static<T> Optional<byte[]> objectToBytes(T obj){
    10         byte[] bytes = null;
    11         ByteArrayOutputStream out = new ByteArrayOutputStream();
    12         ObjectOutputStream sOut;
    13         try {
    14             sOut = new ObjectOutputStream(out);
    15             sOut.writeObject(obj);
    16             sOut.flush();
    17             bytes= out.toByteArray();
    18         } catch (IOException e) {
    19             e.printStackTrace();
    20         }
    21         return Optional.ofNullable(bytes);
    22     }
    23 
    24     public static<T> Optional<T> bytesToObject(byte[] bytes) {
    25         T t = null;
    26         ByteArrayInputStream in = new ByteArrayInputStream(bytes);
    27         ObjectInputStream sIn;
    28         try {
    29             sIn = new ObjectInputStream(in);
    30             t = (T)sIn.readObject();
    31         } catch (Exception e) {
    32             e.printStackTrace();
    33         }
    34         return Optional.ofNullable(t);
    35 
    36     }
    37 }
    38 --------------------- 
    39 作者:idealemail 
    40 来源:CSDN 
    41 原文:https://blog.csdn.net/idealemail/article/details/53993872 
    42 版权声明:本文为博主原创文章,转载请附上博文链接!

      

    by -- 阿圆这个程序媛
  • 相关阅读:
    全能VIP音乐在线解析
    wordpress插件推荐
    day 34 IO模型
    day 33 协程、 socketserver模块
    day 32-2 练习
    day 32-2 并发编程——认识线程(下)
    day 32 练习
    day 32 并发编程——认识线程(上)
    day 31-1 练习
    day 31-1 守护进程、互斥锁、队列、生产消费模型
  • 原文地址:https://www.cnblogs.com/chaos-li/p/9831104.html
Copyright © 2011-2022 走看看