package com.pictc.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; /** * @Description TODO(这里用一句话描述这个类的作用) * @author zhangfucai * @Date 2023年4月25日 上午12:49:14 * @version 1.0.0 */ public class ObjectUtils { private ObjectUtils() { super(); } public static byte[] toBytes(Object obj){ if(obj!=null) { if(!(obj instanceof Serializable)) { throw new RuntimeException(obj+"没有实现 Serializable!"); } ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream oo=null; try { oo = new ObjectOutputStream(out); oo.writeObject(obj); oo.flush(); return out.toByteArray(); } catch (Exception e) { throw new RuntimeException("对象序列化失败!",e); }finally { closeQuietly(oo,out); } } return null; } public static void write(OutputStream out,Object obj) { if(obj!=null) { if(!(obj instanceof Serializable)) { throw new RuntimeException(obj+"没有实现 Serializable!"); } ObjectOutputStream oo=null; try { oo = new ObjectOutputStream(out); oo.writeObject(obj); oo.flush(); } catch (Exception e) { throw new RuntimeException("对象序列化失败!",e); }finally { closeQuietly(oo,out); } } } @SuppressWarnings("unchecked") public static T reader(InputStream in){ ObjectInputStream ois = null; try { ois = new ObjectInputStream(in); return (T) ois.readObject(); } catch (Exception e) { throw new RuntimeException("对象反序列化失败!",e); }finally { closeQuietly(ois,in); } } public static T reader(byte[] bytes){ return reader(new ByteArrayInputStream(bytes)); } public static void closeQuietly(Closeable... closeables) { if (closeables == null) return; for (Closeable closeable : closeables) { if (closeable == null) return; try { closeable.close(); } catch (IOException ignored) { } } } }