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 -- 阿圆这个程序媛
  • 相关阅读:
    webpack to package typescript & scss
    start use webpack
    use selenium+chromedriver to taobao automatically
    Use Hexo to Build My Gitee Blog
    Promise调用方式
    导航守卫用法
    VueCli路由配置
    webpack安装vue-loader
    webpack用npm进行局部安装
    JavaScript里的语句用分号结尾是个选项吗
  • 原文地址:https://www.cnblogs.com/chaos-li/p/9831104.html
Copyright © 2011-2022 走看看