第三次学JAVA再学不好就吃翔(part113)--对象操作流
生活随笔
收集整理的這篇文章主要介紹了
第三次学JAVA再学不好就吃翔(part113)--对象操作流
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
學習筆記,僅供參考,有錯必糾
對象操作流
對象操作流可以將一個對象寫出, 或者讀取一個對象到程序中,也就是執行了序列化和反序列化的操作。
- 舉個例子
先構造一個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;}@Overridepublic 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]創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的第三次学JAVA再学不好就吃翔(part113)--对象操作流的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 惠普(HP)LaserJet Pro P
- 下一篇: 生石灰的成分