对象流的读取
import java.io.*;
import java.util.ArrayList;
//实现对对象的写入和读取
public class Demo1 {
ArrayList<Student> list = new ArrayList<>();
public static void main(String[] args) {
Demo1 demo1 = new Demo1();
demo1.add();
demo1.readToFile();
demo1.fileToObiect();
}
public void add(){
Student lili = new Student("lili", 24);
Student wangwang = new Student("wangwang", 45);
//把数据添加到集合中
list.add(lili);
list.add(wangwang);
}
public void readToFile(){
try {
FileOutputStream fos = new FileOutputStream("C:\\a.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
oos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void fileToObiect(){
FileInputStream fis = null;
try {
fis = new FileInputStream("C:\\a.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
//读取,此时读取的类型是object类型,需要装换成集合类型(需要强转),并把文件里的数据增加到原来集合中
list = (ArrayList<Student>)ois.readObject();
for (Student student : list) {
System.out.println(student);
}
fis.close();
ois.close();
//此时第一次找不到这个文件会报错,所以对这个进行处理
} catch (FileNotFoundException e) {
//e.printStackTrace();
File file = new File("C:\\a.txt");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
}catch (IOException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
import java.io.Serializable;
//在进行对象流操作时,一定要实现Serializable接口
public class Student implements Serializable {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}