美文网首页Java
Serializaton & Deserialization

Serializaton & Deserialization

作者: JaedenKil | 来源:发表于2021-09-29 14:49 被阅读0次

transient is a variables modifier used in serialization. At the time of serialization, if we don’t want to save value of a particular variable in a file, then we use transient keyword. When JVM comes across transient keyword, it ignores original value of the variable and save default value of that variable data type.

import java.io.Serializable;

public class Person implements Serializable {

    public String name;
    public String gender;
    public transient int age;

    Person(String name, String gender, int age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    void showInfo() {
        System.out.printf("Name %s, gender %s, age %d%n", name, gender, age);
    }

}
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SerializationDemo {
    public static void main(String[] args) throws IOException {
        Person person = new Person("Tom", "male", 20);
        FileOutputStream fos = new FileOutputStream("person.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(person);
        oos.flush();
        oos.close();
        fos.flush();
        fos.close();
        person.showInfo();
    }
}
Name Tom, gender male, age 20
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializationDemo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Person person = null;
        FileInputStream fis = new FileInputStream("person.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        person = (Person) ois.readObject();
        fis.close();
        ois.close();
        person.showInfo();
    }
}
Name Tom, gender male, age 0

相关文章

网友评论

    本文标题:Serializaton & Deserialization

    本文链接:https://www.haomeiwen.com/subject/mjsjnltx.html