The code below returns an IOException. Here's my main:
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.");
}
}
This is the Bookstore class which I use just to store the ArrayList of Book objects in orded to use it in Object streams.
public class Bookstore implements Serializable {
private ArrayList<Book> myBooks = new ArrayList<Book>();
public Bookstore(ArrayList<Book> biblia) {
myBooks = biblia;
}
}
I've imported all the right libraries too. What I try to do is: If the file is not empty, then read the ArrayList from there (the bookstore object that contains the arraylist). If it's empty write a new one. The problem is that the only thing I get in returns is "IO Error." and I can't understand why.