JAVA开发基础(使用IO对象操作流)
程序员文章站
2022-07-10 18:51:24
学习笔记,仅供参考,有错必纠对象操作流对象操作流可以将一个对象写出, 或者读取一个对象到程序中,也就是执行了序列化和反序列化的操作。举个例子先构造一个Role类:package com.guiyang.bean;import java.io.Serializable;public class Role implements Serializable {private String name;private int age;public Role() {su...
对象操作流
对象操作流可以将一个对象写出, 或者读取一个对象到程序中,也就是执行了序列化和反序列化的操作。
- 举个例子
先构造一个Role类:
package com.guiyang.bean; import java.io.Serializable; public class Role implements Serializable { private String name; private int age; public Role() { super(); } public Role(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Role [name=" + name + ", age=" + age + "]"; } }
注意,如果要序列化,该类就要实现Serializable
接口.
敲入如下Java代码,将对象存入role.txt:
package com.guiyang.bean; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.security.acl.Permission; public class Demo3_ObjectOutputStream { public static void main(String[] args) throws IOException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("role.txt")); Role p1 = new Role("Ada", 19); Role p2 = new Role("Jack", 20); oos.writeObject(p1); oos.writeObject(p2); oos.close(); } }
我们再读取role.txt文件:
package com.guiyang.bean; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.security.acl.Permission; public class Demo3_ObjectOutputStream { public static void main(String[] args) throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("role.txt")); Role r1 = (Role) ois.readObject(); Role r2 = (Role) ois.readObject(); System.out.println(r1); System.out.println(r2); } }
输出:
Role [name=Ada, age=19]
Role [name=Jack, age=20]
本文地址:https://blog.csdn.net/m0_37422217/article/details/108262241
上一篇: JAVA 多线程 LongAdder和AtomicLong
下一篇: 你还敢不敢了