可以把Java中的对象写到本地文件中
序列化流(对象操作输出流)
构造方法
成员方法
使用对象输出流将对象保存到文件会出现NotSerializableException异常
解决方案:需要让Javabean类实现Serializable接口
Student
package myio;import java.io.Serializable;public class Student implements Serializable {private String name;private int age;public Student() {}public Student(String name, int age) {this.name = name;this.age = age;}/*** 获取* @return name*/public String getName() {return name;}/*** 设置* @param name*/public void setName(String name) {this.name = name;}/*** 获取* @return age*/public int getAge() {return age;}/*** 设置* @param age*/public void setAge(int age) {this.age = age;}public String toString() {return "Student{name = " + name + ", age = " + age + "}";}
}
ObjectStreamDemo
package myio;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;public class ObjectStreamDemo {public static void main(String[] args) throws IOException {Student stu = new Student("zhangsan",20);ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\Web\\API\\src\\myio\\e.txt"));oos.writeObject(stu);oos.close();}
}
反序列化流(对象操作输入流)
构造方法
成员方法
package myio;import java.io.*;public class ObjectStreamDemo2 {public static void main(String[] args) throws IOException, ClassNotFoundException {ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\Web\\API\\src\\myio\\e.txt"));Object o = ois.readObject();System.out.println(o);ois.close();}
}
在这个里面需要注意的是版本号的问题,这样在更改之后不会报错
package myio;import java.io.Serializable;public class Student implements Serializable {private static final long serialVersionUID = 5982546292687225019L;private String name;private int age;public Student() {}public Student(String name, int age) {this.name = name;this.age = age;}/*** 获取* @return name*/public String getName() {return name;}/*** 设置* @param name*/public void setName(String name) {this.name = name;}/*** 获取* @return age*/public int getAge() {return age;}/*** 设置* @param age*/public void setAge(int age) {this.age = age;}public String toString() {return "Student{name = " + name + ", age = " + age + "}";}
}
自动生成这个版本号
复制Serializable
点击Settings
在里面搜索Settings
把下面的这两个勾选上
这样应用到idea中就可以自动生成这个版本号了
如果想要隐藏一些数据,就可以把这个隐藏