The Object that you wrote to the ObjectOutputStream
is called mediaList
, therefore I assume that this is an ArrayList<Media>
rather than each individual Media
object.
On the ObjectInputStream
, you are reading an object and casting it to Media
, but I think that you will find that it is an ArrayList<Media>
(or however mediaList is defined when it is written to the ObjectOutputStream
).
ObjectInputStream instance of
-
30-06-2023 - |
Pregunta
I'm trying to read from a file I have saved using the following code:
public void saveOnFile() {
try {
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("object.txt"));
output.writeObject(mediaList);
output.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
public void readFromFile() {
try {
ObjectInputStream inStream = new ObjectInputStream(new FileInputStream("object.txt"));
this.mediaList.add( (Media) inStream.readObject());
inStream.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
However, I don't know if ObjectInputStream
knows what objects are inputted. Objects in this case can either be a "Movie" or a "TVShow" but the are all subclasses to Media.
I get the following errors:
java.lang.ClassCastException: java.util.ArrayList cannot be cast to project.Media
at project.MediaHandler.readFromFile(MediaHandler.java:66)
at project.Window.<init>(Window.java:73)
at project.Window.main(Window.java:199)
Solución
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow