2011-01-20 74 views
0

下面的代碼返回IOException。這裏是我的主:可序列化ArrayList - 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."); 

     } 

} 

這是我使用的只是書的對象的ArrayList存儲在orded的對象流使用它書店類。

public class Bookstore implements Serializable { 


    private ArrayList<Book> myBooks = new ArrayList<Book>(); 

    public Bookstore(ArrayList<Book> biblia) { 

     myBooks = biblia; 

    } 

} 

我也導入了所有正確的庫。 我試圖做的是:如果文件不是空的,然後從那裏讀取ArrayList(包含數組列表的書店對象)。如果它是空的,請寫一個新的。 問題是我得到的唯一回報是「IO錯誤」。我不明白爲什麼。

+0

你應該多想想如何測試一個文件是否存在:)。你現在這樣做的方式並不真正起作用。 – 2011-01-20 01:30:34

+0

在你的catch(IOException ex2)塊內部添加「ex2.printStackTrace();」以獲得您的例外發生的細節。 – 2011-01-20 01:31:03

回答

1

如果您在得到異常時打印堆棧跟蹤,它將幫助您調試這些問題,但我猜測該書不可序列化。

2

這是測試文件是否存在的錯誤方法。您正嘗試從不存在的文件創建流,並引發FileNotFoundException。相反的:

FileInputStream fis = new FileInputStream("objects");    
int u = fis.read(); 
if (u != -1) { 

只使用

if(f.exists()) { ... } 
0

Nightsorrow可能是正確的。爲了回答你爲什麼得到「IO錯誤」,這是因爲你告訴程序打印,如果有IO錯誤。爲了調試您的代碼,我將刪除代碼段或註釋它,以便您可以獲取堆棧跟蹤。然後,您可以精確定位錯誤發生的位置和原因,因爲它會給您一個異常,並拋出異常。