ObjectInputStream和ObejctOutputStream
生活随笔
收集整理的這篇文章主要介紹了
ObjectInputStream和ObejctOutputStream
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
ObjectInputStream和ObejctOutputStream的作用是:對(duì)基本數(shù)據(jù)和對(duì)象進(jìn)行序列化支持.
ObjectOutputStream提供對(duì)"基本數(shù)據(jù)對(duì)象"的持久存儲(chǔ).ObjectInputStream提供對(duì)"基本數(shù)據(jù)對(duì)象"的讀取.
public class ObjectStreamTest {private static final String PATH = "D:\\baiduyun\\filetest\\rrr.txt";public static void main(String[] args) throws Exception {testWrite();testRead();}public static void testWrite() throws FileNotFoundException, IOException {ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(PATH)));out.writeBoolean(true);out.writeByte((byte) 65);out.writeChar('a');out.writeInt(20131015);out.writeFloat(3.14F);out.writeDouble(1.414D);// 寫入HashMap對(duì)象HashMap map = new HashMap();map.put("one", "red");map.put("two", "green");map.put("three", "blue");out.writeObject(map);// 寫入自定義的Box對(duì)象,Box實(shí)現(xiàn)了Serializable接口Box box = new Box("desk", 80, 48);out.writeObject(box);out.close();}public static void testRead() throws FileNotFoundException, IOException, ClassNotFoundException {ObjectInputStream in = new ObjectInputStream(new FileInputStream(PATH));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對(duì)象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對(duì)象,Box實(shí)現(xiàn)了Serializable接口Box box = (Box) in.readObject();System.out.println("box: " + box);in.close();}static class Box implements Serializable {private int width;private int height;private String name;public Box(String name, int width, int height) {this.name = name;this.width = width;this.height = height;}@Overridepublic String toString() {return "[" + name + ": (" + width + ", " + height + ") ]";}} }?
轉(zhuǎn)載于:https://www.cnblogs.com/zhangj-ymm/p/9861360.html
總結(jié)
以上是生活随笔為你收集整理的ObjectInputStream和ObejctOutputStream的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 012 循环
- 下一篇: EF Core 生成数据库