1.先创建一个软件包,取名为sei(可随意)
2.在sei里面建一个Student的类
package com.example.sei;
import java.io.Serializable;
//学生类,姓名,年龄
//Serializable
public class Student implements Serializable {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
3.在建一个TestStudent的类
package com.example.sei;
import java.io.*;
public class TestStudent {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Student student = new Student("John", 20);
System.out.println(student.name + " " + student.age );
//java序列化:把对象保存到一个文件中
//1.让这个类实现Serializable接口
//2.创建一个输出流
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student_java.ser"));
//3.把对象写入到文件中
oos.writeObject(student);
//4.关闭
oos.close();
}
}
这个就是Java序列化
package com.example.sei;
import java.io.*;
public class TestStudent {
public static void main(String[] args) throws IOException, ClassNotFoundException {
// Student student = new Student("John", 20);
// System.out.println(student.name + " " + student.age );
//
//
// //java序列化:把对象保存到一个文件中
// //1.让这个类实现Serializable接口
// //2.创建一个输出流
// ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student_java.ser"));
// //3.把对象写入到文件中
// oos.writeObject(student);
// //4.关闭
// oos.close();
//java反序列化:从文件student_java.ser中读出内容,还原这个对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student_java.ser"));
Student student = (Student) ois.readObject();
System.out.println(student.name + " " + student.age );
}
}
4

被折叠的 条评论
为什么被折叠?



