java readunshared_java io系列05之 ObjectInputStream 和 ObjectOutputStream

/*** ObjectInputStream 和 ObjectOutputStream 测试程序

*

* 注意:通过ObjectInputStream, ObjectOutputStream操作的对象,必须是实现了Serializable或Externalizable序列化接口的类的实例。

*

*@authorskywang*/

importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;importjava.io.Serializable;importjava.util.Map;importjava.util.HashMap;importjava.util.Iterator;public classObjectStreamTest {private static final String TMP_FILE = "box.tmp";public static voidmain(String[] args) {

testWrite();

testRead();

}/*** ObjectOutputStream 测试函数*/

private static voidtestWrite() {try{

ObjectOutputStream out= newObjectOutputStream(newFileOutputStream(TMP_FILE));

out.writeBoolean(true);

out.writeByte((byte)65);

out.writeChar('a');

out.writeInt(20131015);

out.writeFloat(3.14F);

out.writeDouble(1.414D);//写入HashMap对象

HashMap map = newHashMap();

map.put("one", "red");

map.put("two", "green");

map.put("three", "blue");

out.writeObject(map);//写入自定义的Box对象,Box实现了Serializable接口

Box box = new Box("desk", 80, 48);

out.writeObject(box);

out.close();

}catch(Exception ex) {

ex.printStackTrace();

}

}/*** ObjectInputStream 测试函数*/

private static voidtestRead() {try{

ObjectInputStream in= newObjectInputStream(newFileInputStream(TMP_FILE));

System.out.printf("boolean:%b\n", in.readBoolean());

System.out.printf("byte:%d\n" , (in.readByte()&0xff));

System.out.printf("char:%c\n", in.readChar());

System.out.printf("int:%d\n", in.readInt());

System.out.printf("float:%f\n", in.readFloat());

System.out.printf("double:%f\n", in.readDouble());//读取HashMap对象

HashMap map =(HashMap) in.readObject();

Iterator iter=map.entrySet().iterator();while(iter.hasNext()) {

Map.Entry entry=(Map.Entry)iter.next();

System.out.printf("%-6s -- %s\n", entry.getKey(), entry.getValue());

}//读取Box对象,Box实现了Serializable接口

Box box =(Box) in.readObject();

System.out.println("box: " +box);

in.close();

}catch(Exception e) {

e.printStackTrace();

}

}

}class Box implementsSerializable {private intwidth;private intheight;privateString name;public Box(String name, int width, intheight) {this.name =name;this.width =width;this.height =height;

}

@OverridepublicString toString() {return "["+name+": ("+width+", "+height+") ]";

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值