- package per.mjn.serializable;
-
- import java.io.Serializable;
-
- /**
- * 对象要序列化,必须实现Serializable序列化接口
- */
- public class Student implements Serializable {
-
- private String name;
- private String loginName;
- private String password;
- private int age;
-
- @Override
- public String toString() {
- return "Student{" +
- "name='" + name + '\'' +
- ", loginName='" + loginName + '\'' +
- ", password='" + password + '\'' +
- ", age=" + age +
- '}';
- }
-
- public Student() {
- }
-
- public Student(String name, String loginName, String password, int age) {
- this.name = name;
- this.loginName = loginName;
- this.password = password;
- this.age = age;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getLoginName() {
- return loginName;
- }
-
- public void setLoginName(String loginName) {
- this.loginName = loginName;
- }
-
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
- }
- package per.mjn.serializable;
-
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.ObjectOutputStream;
-
- /**
- * 对象序列化,使用ObjectOutputStream将内存中的对象存入磁盘文件中
- */
- public class ObjectOutputStreamDemo1 {
- public static void main(String[] args) throws IOException {
- // 1. 创建学生对象
- Student s = new Student("mjn", "mjn", "1111", 22);
-
- // 2. 对象序列化,使用对象字节输出流包装字节输出流管道
- ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("d:/obj.txt"));
-
- // 3. 直接调用序列化方法
- objectOutputStream.writeObject(s);
-
- // 4. 释放资源
- objectOutputStream.close();
- System.out.println("序列化完成");
- }
- }