对象序列化ObjectOutputStream,ObjectInputStream

来源:互联网 发布:linux重启服务器命令 编辑:程序博客网 时间:2024/05/01 13:35

int---->4 byte 流

long---->8 byte 流

String 5个字符(GBK编码)----->10 byte 流

Object---->n byte 流

1.ObjectOutputStream,ObjectInputStream

readObject

writeObject(obj)

package ObjectStreamDemo;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;public class ObjectStreamDemo {public static void main(String[] args) throws IOException, ClassNotFoundException {ByteArrayOutputStream out=new ByteArrayOutputStream();ObjectOutputStream os=new ObjectOutputStream(out);Foo user=new Foo(5, "lirui");os.writeObject(user);os.close();byte[] bt=out.toByteArray();String str=ToHexStringFromByte(bt);System.out.println(str);ObjectInputStream is=new ObjectInputStream(new ByteArrayInputStream(bt));Object man=is.readObject();if(man instanceof Foo){Foo foo=(Foo)man;System.out.println(foo.id+" "+foo.name);}}private static String ToHexStringFromByte(byte[] bt) {StringBuilder str=new StringBuilder();for (byte b : bt) {int data=0xff&b;str.append(Integer.toHexString(data)+" ");}return str.toString();}}
package ObjectStreamDemo;import java.io.Serializable;@SuppressWarnings("serial")public class Foo implements Serializable{//要求必须实现序列化接口int id;String name;public Foo(int id, String name) {super();this.id = id;this.name = name;}}



原创粉丝点击