对象操作流
该流可以将一个对象写出, 或者读取一个对象到程序中. 也就是执行了序列化和反序列化的操作.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | ObjectOutputStream new ObjectOutputStream(OutputStream), writeObject() public class Demo3_ObjectOutputStream { public static void main(String[] args) throws IOException { Person p1 = new Person( "张三" , 23 ); Person p2 = new Person( "李四" , 24 ); ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream( "e.txt" )); //创建对象输出流 oos.writeObject(p1); oos.writeObject(p2); oos.close(); } } |
ObjectInputStream
new ObjectInputStream(InputStream), readObject()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class Demo3_ObjectInputStream { public static void main(String[] args) throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream( new FileInputStream( "e.txt" )); Person p1 = (Person) ois.readObject(); Person p2 = (Person) ois.readObject(); System.out.println(p1); System.out.println(p2); ois.close(); } } |
对象操作流优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | Person p1 = new Person( "张三" , 23 ); Person p2 = new Person( "李四" , 24 ); Person p3 = new Person( "马哥" , 18 ); Person p4 = new Person( "辉哥" , 20 ); ArrayList<Person> list = new ArrayList<>(); list.add(p1); list.add(p2); list.add(p3); list.add(p4); ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream( "f.txt" )); oos.writeObject(list); //写出集合对象 oos.close(); |
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步