对象的输出流: ObjectOutputStream
对象的输入流: ObjectInputStream
java.io.ObjectOutputStream是实现序列化的关键类,它可以将一个对象转换成二进制流,然后可以通过ObjectInputStream将二进制流还原成对象。
主要的作用是用于写入对象信息与读取对象信息。 对象信息一旦写到文件上那么对象的信息就可以做到持久化了
需要序列化的类必须实现java.io.Serializable接口,否则会抛出NotSerializableException异常 ,所以我们都要加上import java.io.*; 这个类
package HelloWorld;
import java.io.*;
import java.util.*;
public class Main {//对象流
public static void main(String[] args){
try(ObjectOutputStream out =new ObjectOutputStream(new FileOutputStream("test.txt"));//查找test.txt文件若没找到则创建一个名为test.txt的文件
ObjectInputStream in= new ObjectInputStream(new FileInputStream("test.txt"))){//从文件test.txt中读取数据
List<String> list= new ArrayList<>(Arrays.asList("a","b","c"));
out.writeObject(list); ///把一个对象以某种方式序列化后存入文件中
Object o=in.readObject();
System.out.println(o);//在控制台打印从文件中读出的数据
}catch (IOException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
在通过类使用对象流将数据存入文件中。
Java的序列化会将一个类包含的引用中所有的成员变量保存下来(深度复制),所以里面的引用类型必须也要实现java.io.Serializable接口。
package HelloWorld;
import java.io.*;
class Person implements Serializable {
String name;
int age;
Person(String name,int age){
this.age=age;
this.name=name;
}
public String toString(){
return name+" "+age;
}
}
public class Main {//对象流
public static void main(String[] args) throws IOException {
FileOutputStream fos=new FileOutputStream("out.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
Person p=new Person("LZF",19);
oos.writeObject(p);
oos.close();;
System.out.println(p);
}
}