Java序列化

tech2024-06-25  67

序列化就是做持久化存储数据。将整个对象信息进行存储在硬盘上。

代码

1、创建Student类

public class Student implements Serializable { private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

2、StudentTestMain

public class StudentTestMain { public static void main(String[] args) throws Exception { //将对象存入桌面 // Student student = new Student(); // student.setAge(20); // student.setName("wu"); // ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("C:\\Users\\HP\\Desktop\\student.txt")); // out.writeObject(student); // out.close(); // //将存入桌面的对象调入内存当中 Student student; ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:\\\\Users\\\\HP\\\\Desktop\\\\student.txt")); student = (Student) in.readObject(); System.out.println(student.getAge() +" "+ student.getName()); } }
最新回复(0)