I am presently working on a simple ObjectInputStream
and ObjectOutputStream
, I have read both the documentation and the Java tutorial and am familiar with the basics; however, in attempting to compile my program, I am encountering an error that may be related to my misunderstanding of the combination of Map
s and Object input/output, specifically the input portion.
I have a .dat file, from which I am trying to read a list of objects that get mapped into a TreeMap
:
public class Product implements Serializable
{
private static final long serialVersionUID = 1L;
private int code;
private String name;
private int quatity;
// Setters and Getters
}
Above, is the code fragment for the Product
object, itself - implementing Serializable
. I include the fragment in case the problem lies, there.
For this question, assume the .dat is not empty and contains properly formatted data.
Here is my ObjectInputStream
code:
try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file))) {
while (true) {
try {
products = (Map<Integer, Product>) inputStream.readObject();
}
catch (ClassNotFoundException cnfException {
System.out.println("ClassNotFoundException: " + cnfException.getMessage());
}
catch (EOFException eofException) {
System.err.println("EOFException: " + eofException.getMessage());
}
}
When attempting to run this code, I get the following error (a Cast error):
Here is how I am writing Product
objects to the .dat file:
try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileName))) {
for (int i = 0; i < products.size(); i++) {
outputStream.writeObject(products.get(i));
}
}
Having isolated the error, I know the error occurs when I hit the products =
portion. I am unsure if this is a compound issue or if this is one of two issues:
- I am not properly grabbing the data from the file in order to populate the
TreeMap
- I am misunderstanding the implementation of
ObjectInputStream