如题,想从文件读取一个包含自定义类型的ArrayList,然后存到list中,但是不知道为什么报错,求看看
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
public class Test {
static ArrayList<Book> list = new ArrayList<Book>();
public static void main(String[] args) throws Exception {
readObject();
}
public static void readObject() throws Exception {
ObjectInputStream in = null;
FileInputStream fin = null;
File file = new File("src/test.txt");
if(file.exists()) {
fin = new FileInputStream(file);
in = new ObjectInputStream(fin);
list = (ArrayList<Book>) in.readObject();
}else {
file.createNewFile();
}
fin.close();
in.close();
}
}
简化后:
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
public class Test {
static ArrayList<Book> l = new ArrayList<Book>();
public static void main(String[] args) throws Exception {
readObject();
}
public static void readObject() throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src/test.txt"));
l = (ArrayList<Book>) ois.readObject();
ois.close();
}
}