对象序列化及反序列化
程序员文章站
2022-03-22 15:25:21
...
import java.io.*; public class Demo { public static void main(String[] args) throws IOException, ClassNotFoundException { String filename = "file.dat"; /** * 将对象写入文件 */ ObjectOutputStream obj = new ObjectOutputStream( new FileOutputStream(filename)); Student s = new Student("boy", "James", 1); obj.writeObject(s); /** * 将对象读出文件 */ ObjectInputStream objIn = new ObjectInputStream( new FileInputStream(filename)); Student std = (Student)objIn.readObject(); // 此处 readObject() 方法返回的是 Object 对象,必须强制转换 System.out.println(std); // ID = 1 Name = James Sex = null objIn.close(); obj.close(); } } class Student implements Serializable { // 如果要将一个对象序列化,必须实现 Serializable private String name; private int id; private transient String sex; // transient 关键字表示该属性不可序列化 public Student () { } public Student (String sex, String name, int id) { this.sex = sex; this.name = name; this.id = id; } public int getId() { return this.id; } public String getName() { return this.name; } public String getSex() { return this.sex; } @Override public String toString() { return ("ID = " + this.getId() + " " + "Name = " + this.getName() + " " + "Sex = " + this.getSex()); } }
上一篇: qq浏览器 不支持css3怎么办
下一篇: mybatis反向工程的介绍(代码示例)