1,ObjecOutputStream是对象操作流
-
该流可以将一个对象写出, 或者读取一个对象到程序中. 也就是执行了序列化和反序列化的操作.
-
序列化就是按文档的规定写入 (存档)
-
反序列化就是按文档的规定读出 (读档)
-
ObjecOutputStream。存放对象。
2,使用方式
【1】bean:
import java.io.Serializable;
public class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2L;
private String name;
private int age;
public Person() {
super();
}
public Person(String name, int age) {
super();
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;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
【2】ObjectOutputStream 写入文件序列化(里面的是乱码,但对本身没有关系 )
public static void demo1() throws IOException, FileNotFoundException {
Person p1 = new Person("张三", 23);
Person p2 = new Person("李四", 24);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("e.txt"));
oos.writeObject(p1);
oos.writeObject(p2);
oos.close();
}
【3】ObjectInputStream 读取文件 反序列化(如果没有读到文件的对象,会报异常EOFExcption)
public static void demo1() throws IOException, FileNotFoundException,
ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e.txt"));
Person p1 = (Person) ois.readObject();
Person p2 = (Person) ois.readObject();
//Person p3 = (Person) ois.readObject(); //当文件读取到了末尾时出现EOFException
System.out.println(p1);
System.out.println(p2);
ois.close();
}
【4】把数据写在集合里一次写出
public static void main(String[] args) throws IOException {
//demo1();
Person p1 = new Person("张三", 23);
Person p2 = new Person("李四", 24);
Person p3 = new Person("王五", 25);
Person p4 = new Person("赵六", 26);
ArrayList<Person> list = new ArrayList<>();
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("e.txt"));
oos.writeObject(list); //把整个集合对象一次写出
oos.close();
}
【5】把数据一次性读取(对象输入流,反序列化)
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
//demo1();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e.txt"));
ArrayList<Person> list = (ArrayList<Person>) ois.readObject(); //将集合对象一次读取
for (Person person : list) {
System.out.println(person);
}
ois.close();
}

本文介绍了JAVA中的ObjecOutputStream,用于执行对象的序列化和反序列化操作。序列化是将对象按标准写入,而反序列化则是按标准读出对象。内容包括bean的操作,以及如何使用ObjectOutputStream进行文件序列化,ObjectInputStream进行文件反序列化,同时讲解了如何处理集合的序列化和反序列化操作。
1693

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



