Serializable ArrayList -- IOException error
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 开发者_如何学Pythoncontains 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.
It's wrong way to test if file exists. You are trying create stream from file which doesn't exists, and FileNotFoundException is thrown. Instead of:
FileInputStream fis = new FileInputStream("objects");
int u = fis.read();
if (u != -1) {
just use
if(f.exists()) { ... }
It would help you debug these problems if you printed the stack trace when you get an exception, but I am guessing that Book is not serializable.
Nightsorrow is probably right. To answer why you are getting "IO Error" out, it is because you told the program to print that if there was an IO Error. For the purposes of debugging your code I would delete the
catch (IOException ex2) {
System.out.println("IO Error.");
}
section of your code or comment it out so that you can get the stack trace. Then you can pinpoint where and why the error is occuring because it will give you an exception and what line that exception was thrown.
精彩评论