您的位置:首页 > 移动开发 > Objective-C

对象序列化ObjectOutputStream,ObjectInputStream

2013-11-22 08:55 579 查看
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;
}
}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐