展开全部
可以使用 ObjectOutputStream 将对象写入文件中,使用 ObjectInputStream 类从文件中读取出对象。
代码如下32313133353236313431303231363533e4b893e5b19e31333365643562:import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
class Person implements Serializable {
private static final long serialVersionUID = -3527230407404080537L;
private String name;
private int age;
public Person(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;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
public class App34 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
List persons = new ArrayList<>();
persons.add(new Person("张三", 20));
persons.add(new Person("李四", 25));
File file = new File("persons.data");
// 创建文件输出流
FileOutputStream output = new FileOutputStream(file);
// 创建对象输出流
ObjectOutputStream oOutput = new ObjectOutputStream(output);
// 将整个数组列表输出至文件
oOutput.writeObject(persons);
// 或者逐个将对象输出至文件,读取时需要逐个读取
/*for (Person p : persons) {
oOutput.writeObject(p);
}*/
oOutput.close();
output.close();
// 创建文件输入流
FileInputStream input = new FileInputStream(file);
// 创建对象输入流
ObjectInputStream oInput = new ObjectInputStream(input);
// 读出整个对象列表
List persons2 = (List) oInput.readObject();
for (Person p : persons2) {
System.out.println(p);
}
// 或者逐个读取对象
/*Person p1 = null;
try {
while((p1 = (Person) oInput.readObject()) != null) {
System.out.println(p1);
}
} catch (EOFException e) {
System.out.println("读取对象结束");
}*/
oInput.close();
input.close();
}
}