Search code examples
javaobjectinputstreamtreemaps

Reading Objects From A File to An Input Stream


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 Maps 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):

Screenshot of Error Message

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:

  1. I am not properly grabbing the data from the file in order to populate the TreeMap
  2. I am misunderstanding the implementation of ObjectInputStream

Solution

  • It sounds like you originally just wrote the Product objects to an ObjectOutputStream, rather than a Map<Integer, Product>. If that's the case, you need something like:

    Map<Integer, Product> products = new TreeMap<>();
    try (ObjectInputStream input = new ObjectInputStream(new FileInputStream(file))) {
        while (true) {
            Product product = (Product) input.readObject();
            products.put(product.getCode(), product); // Or whatever
        }
    } catch (EOFException e) {
        // Just finish? Kinda nasty...
    }
    

    Of course, that will throw an exception when it reaches the end of the stream - you might want to think about how you're going to detect that cleanly rather than just handling the exception.