2013-10-09 143 views
0

好了,所以我有一個「動物」類,它是抽象與子「狗」和「鳥」我需要編寫一個程序來讀取和二進制數目不詳的動物對象文件。從二進制文件中讀取對象的任意數量

public static void main(String[] args) throws FileNotFoundException { 
    readAnimals("birdsAndDogs.dat"); 

} 

public static List<Animal> readAnimals(String filename) { 
    List<Animal> animals = new ArrayList<Animal>(); 
    ObjectInputStream ois = null; 
    try { 
     ois = new ObjectInputStream(new FileInputStream(filename)); 

     try { 
      while (true) { 
       Animal a =(Animal) ois.readObject(); 

       if (a instanceof Animal) 
        animals.add((Animal)a); 
       System.out.println(a); 
      } 
     } 
     catch (EOFException eof) { 
      ois.close(); 
      ois = null; 
      return animals; 
     } 
    } 
    catch (Exception e) { 
     return null; 
    } 
} 
} 

這是我第一次嘗試讀取二進制文件,所以慢慢來,該代碼可能是相當混亂,我不知道,但我的主要問題是我不斷收到一個FileNotFoundExeption,但該文件是在相同的包裝和位置,有什麼想法?

也就是它的代碼自我結構正確?

感謝您的任何和所有幫助

回答

1

當應用程序看到

new FileInputStream("justADog.dat") 

它會在應用程序被啓動目錄的文件名。我很懷疑你的應用程序從包類是在跑。

要麼提供完整的文件路徑或文件移動到您的應用程序從運行的位置。使用Eclipse,應用程序從您的項目文件夾啓動。

+0

他們是在同一個項目文件夾,還當我從性能得到完整的路徑我仍然有同樣的問題。 – user2745043

+0

@user誰是_they_? –

+0

我試圖測試的二進制文件和所有類 – user2745043