java – 将对象强制转换为byteArray
发布时间:2020-12-15 05:08:37 所属栏目:Java 来源:网络整理
导读:我有一个功能 public static Object receviceSigAndData (Socket s) { byte[] data = null; try { DataInputStream din2 = new DataInputStream(s.getInputStream()); int sig_len = 0; sig_len = din2.readInt(); byte[] sig = new byte[sig_len]; din2.rea
我有一个功能
public static Object receviceSigAndData (Socket s) { byte[] data = null; try { DataInputStream din2 = new DataInputStream(s.getInputStream()); int sig_len = 0; sig_len = din2.readInt(); byte[] sig = new byte[sig_len]; din2.readFully(sig); int data_len = 0; data_len = din2.readInt(); data = new byte[data_len]; dsa.update(data); } catch (IOException ioe) { ioe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return (Object)data; } 函数返回一个对象,如果对象是字节数组,我该如何将对象转换为byte []? byte[] b = (?)receviceSigAndData (socket); 谢谢 解决方法
下面是两个辅助方法,可以将字节数组序列化和反序列化为对象.
public static Object deserializeBytes(byte[] bytes) throws IOException,ClassNotFoundException { ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bytesIn); Object obj = ois.readObject(); ois.close(); return obj; } public static byte[] serializeObject(Object obj) throws IOException { ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bytesOut); oos.writeObject(obj); oos.flush(); byte[] bytes = bytesOut.toByteArray(); bytesOut.close(); oos.close(); return bytes; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读