import java.io.Serializable;
public class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 3L; //可以加也可以不加,加就是为了让大家更清楚的看懂异常
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 + "]";
}
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import cn.itcast.bean.Person;
public class Demo3_ObjectOutputStream {
/**
* @param args
* @throws IOException
* 序列化,将对象写到文件上
*/
public static void main(String[] args) throws IOException {
//demo1();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c.txt")); //创建输出流对象
Person p1 = new Person("张三", 23); //创建人对象
Person p2 = new Person("李四", 24);
ArrayList<Person> list = new ArrayList<>(); //创建集合对象
list.add(p1); //将人添加到集合中
list.add(p2);
oos.writeObject(list); //写出集合对象
oos.close(); //关流
}
private static void demo1() throws IOException, FileNotFoundException {
Person p1 = new Person("张三", 23);
//FileOutputStream fos = new FileOutputStream("b.txt");
//fos.write(); 字节流不能写出对象
//FileWriter fw = new FileWriter("b.txt");
//fw.write(p1); 字符输出流不能写出对象
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("b.txt")); //创建对象输出流,关联b.txt
oos.writeObject(p1); //写出一个对象
oos.close();
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;
import cn.itcast.bean.Person;
public class Demo4_ObjectInputStream {
/**
* @param args
* @throws IOException
* @throws FileNotFoundException
* @throws ClassNotFoundException
* 反序列化,将文件上数据读取出来
*/
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
//demo1();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("c.txt")); //创建对象输入流对象,关联c.txt
List<Person> list = (List<Person>) ois.readObject(); //读取对象
for (Person person : list) { //遍历集合
System.out.println(person);
}
ois.close(); //关流
}
private static void demo1() throws IOException, FileNotFoundException,
ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("b.txt")); //创建对象输入流,关联b.txt
Person p1 = (Person) ois.readObject(); //读取对象
//Person p2 = (Person) ois.readObject(); //读取对象
System.out.println(p1); //输出
//System.out.println(p2); //输出
ois.close();
}
}
|
|