Reputation: 199
Ok so I have an 'Animal' class that is abstract with subclasses 'Dog' and 'Bird' I need to write a program to read and unknown number of Animal objects from a binary file.
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;
}
}
}
This is my first time trying to read binary files, so take it easy, the code may be pretty messy I'm not sure but my main problem is I keep getting a FileNotFoundExeption, but the file is in the same package and location, any ideas?
also is the code it self structured correctly?
Thanks for any and all help
Upvotes: 0
Views: 257
Reputation: 280138
When the application sees
new FileInputStream("justADog.dat")
it looks for the file name in the directory the application was launched from. I very much doubt your application was ran from the package your class is in.
Either provide a full path to the file or move the file to the location your application is ran from. With Eclipse, the application is started from your project folder.
Upvotes: 1