java的序列化和反序列化,【序列化與反序列化流】

 2023-12-25 阅读 30 评论 0

摘要:package test;import java.io.*;/*** @author shusheng* @description 序列化與反序列化流* @Email shusheng@yiji.com* @date 2018/12/23 16:49*/ public class ObjectStreamDemo {//當有些變量不需要序列化時使用 transient 關鍵字申明不需要序列化的成
package test;import java.io.*;/*** @author shusheng* @description 序列化與反序列化流* @Email shusheng@yiji.com* @date 2018/12/23 16:49*/
public class ObjectStreamDemo {//當有些變量不需要序列化時使用 transient 關鍵字申明不需要序列化的成員變量public static void main(String[] args) throws IOException, ClassNotFoundException {//序列化數據其實就是把對象寫到文本文件中
        write();//反序列化
        read();}private static void read() throws IOException, ClassNotFoundException {//創建反序列化對象ObjectInputStream ois = new ObjectInputStream(new FileInputStream("a.txt"));Object obj = ois.readObject();//釋放資源
        ois.close();//輸出對象
        System.out.println(obj);}private static void write() throws IOException {//創建序列化對象ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("a.txt"));//創建對象Person p= new Person("林青霞",27);//public final void writeObject(Object obj)
        oos.writeObject(p);//釋放資源
        oos.close();}}class Person implements Serializable{private static final long serialVersionUID = 2476243158969951686L;private String name;private int age;public Person(String name, int age) {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 "Person{" +"name='" + name + '\'' +", age=" + age +'}';}
}

?

轉載于:https://www.cnblogs.com/zuixinxian/p/10340689.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/194903.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息