下面的代码返回一个 IOException。这是我的主要内容:
public class Main
{
public static void main(String[] args) {
Book b1 = new Book(100, "The Big Book of Top Gear 2010", "Top Gear",
"BBC Books", 120, "Book about cars.");
Book b2 = new Book(200, "The Da Vinci Code", "Dan Brown", "Vatican", 450,
"A fast paced thriller with riddles.");
Book b3 = new Book(300, "Le Petit Nicolas", "Sempe Goscinny", "Folio", 156,
"The adventures of petit Nicolas.");
ArrayList<Book> biblia = new ArrayList<Book>();
biblia.add(b1);
biblia.add(b2);
biblia.add(b3);
File f = new File("objects");
try {
FileInputStream fis = new FileInputStream("objects");
int u = fis.read();
if (u != -1) {
ObjectInputStream ois = new ObjectInputStream(fis);
Bookstore b = (Bookstore) ois.readObject();
ois.close();
} else {
Bookstore b = new Bookstore(biblia);
FileOutputStream fos = new FileOutputStream("objects");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(b);
oos.close();
}
} catch (FileNotFoundException ex1) {
System.out.println("File not found.");
} catch (IOException ex2) {
System.out.println("IO Error.");
} catch (ClassNotFoundException ex3) {
System.out.println("Class not found.");
}
}
这是我用来存储 Book 对象的 ArrayList 以便在对象流中使用它的 Bookstore 类。
public class Bookstore implements Serializable {
private ArrayList<Book> myBooks = new ArrayList<Book>();
public Bookstore(ArrayList<Book> biblia) {
myBooks = biblia;
}
}
我也导入了所有正确的库。我尝试做的是:如果文件不为空,则从那里读取 ArrayList(包含 arraylist 的书店对象)。如果它是空的,请写一个新的。问题是我返回的唯一内容是“IO 错误”。我不明白为什么。