Reading two different objects from file
I am trying to read 2 arraylists using the following methods.
public static ArrayList<Contestant> readContestantsFromFile() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("minos.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Contestant> contestants = (ArrayList<Contestant>) ois.readObject();
ois.close();
return contestants;
}
public static ArrayList<Times> readContestantsFromFile() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("minos.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<times> times = (ArrayList<Times>) ois.readObject();
ois.close();
return times;
}
Bit this doesn't work. It cannot cast to the the second arraylist type i've saved. So how can I access this? The exact error I got was this:
Exception in thread "main" java.lang.ClassCastException: com.deanchester.minos.model.Contestant cannot be c开发者_运维问答ast to com.deanchester.minos.model.Times
at com.deanchester.minos.tests.testAddTime.main(testAddTime.java:31)
The line that this is referring to is:
ArrayList<times> times = (ArrayList<Times>) ois.readObject();
So how can I read 2 different arraylists from one file?
Use FileOutputStream fos = new FileOutputStream("minos.dat", true);
when writing the second file. true
is a value of argument "append". Otherwise you override the file content. This is the reason that you read the same collection twice.
When you are reading the second collection from the file you have to skip to the beginning of the second collection. To do this you can remember how many bytes have you read on first phase and then use method skip()
.
But better solution is to open file only once (I mean call new FileInputStream and new FileOutputStream) only once and then pass it to methods that read collections.
You can read two different objects from a file using a ObjectInputStream
, but your problem comes from the fact that you reopen the stream so it starts at the beginning of the file where you have the ArrayList<Contestant>
and then you ArrayList<Times>
. Try doing everything at once and returning both lists:
public static ContestantsAndTimes readObjectsFromFile() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("minos.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Contestant> contestants = (ArrayList<Contestant>) ois.readObject();
ArrayList<Times> times = (ArrayList<Times>) ois.readObject();
ois.close();
return new ContestantsAndTimes(contestants, times);
}
精彩评论