序列化:把对象存储到文件中
package MONA.demo10_序列化流;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* 序列化
* Java的对象,将对象存入文件中
* 反序列化
* 将文件中的对象读取到Java内存中
*
* 在序列化对一个对象时会出现异常:
* NotSerializableException
* 解决:需要实现序列化的类
*/
public class Demo01 {
// Serializable:序列化的接口
public static void main(String[] args) throws Exception{
Student s = new Student("李四",19);
//将s对象存入文件中
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student"));
oos.writeObject(s);
oos.close();
System.out.println("写入成功");
}
}
class Student implements Serializable {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
将文件中的对象读取到内存中
package MONA.demo10_序列化流;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
/**
* 反序列化
* 将文件中的对象读取到内存中
*/
public class Demo02 {
public static void main(String[] args) throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student"));
//读取
Object o = ois.readObject();
//将对象转回真正的类型
Student s = (Student) o;
System.out.println(s.getName());
System.out.println(s.getAge());
}
}
eclipse版本需要添加序列号
对象流细节问题
ArrayList也实现了接口Serializable
package MONA.demo10_序列化流;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class Demo01 {
public static void main(String[] args) throws Exception {
ArrayList<String> names = new ArrayList<>();
names.add("李四");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student"));
oos.writeObject(names);
System.out.println("写入成功");
}
}
打印流
package MONA.demo12_打印流;
import java.io.PrintStream;
public class Demo01 {
public static void main(String[] args) throws Exception {
PrintStream p = new PrintStream("1.txt");
p.write(97);
p.println(97);
System.out.println("成功");
}
}