October 22, 2024
Chicago 12, Melborne City, USA
java

Optional Data Exception false when reading object from file


I am trying to read objects from file to display them on a jpanel but I am having a hard time deserializing them.

public static void saveFile(Screen screen)
{
    JFileChooser find = new JFileChooser();
    find.setCurrentDirectory(new File(System.getProperty("user.dir")));
    int result = find.showSaveDialog(find);
    if(JFileChooser.APPROVE_OPTION == result)
    {
        File file = find.getSelectedFile();
        try
        {
            FileOutputStream fo = new FileOutputStream(file);
            ObjectOutputStream os = new ObjectOutputStream(fo);
            os.writeInt(screen.getObjects().size());
            ImageIO.write(screen.getBackgroundImage(), "png", os);
            for(Item i : screen.getObjects())
            {
                i.removeImage();
                os.writeObject(i);
            }
            os.close();
            fo.close();
            for(Item i : screen.getObjects())
            {
                i.setImg();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}
public static Screen loadFile()
{
    JFileChooser find = new JFileChooser();
    find.setCurrentDirectory(new File(System.getProperty("user.dir")));
    int result = find.showOpenDialog(find);
    if(JFileChooser.APPROVE_OPTION == result)
    {
        File file = find.getSelectedFile();
        try
        {
            FileInputStream fi = new FileInputStream(file);
            ObjectInputStream is = new ObjectInputStream(fi);
            int items = is.readInt();
            BufferedImage background = ImageIO.read(is);
            Screen screen = new Screen();
            screen.setBackground(background);
            for(int i = 0; i <= items; i++)
            {
                Item object = (Item) is.readObject();
                object.setImg();
                screen.addObject(object);
            }
            is.close();
            fi.close();
            return screen;
        }
        catch(OptionalDataException e)
        {
            System.out.println(e.eof);
            e.printStackTrace();
            return null;
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }
}

The screen and item objects both implement Serializable and the eof is returning false with integers following the background image. The item objects all have buffered images that I have made draggable on the jpanel. Since buffered images aren’t really serializable, I am removing the images from the objects and then writing them to the file, then re adding them after the write is done for continued use and trying to remake them when the item object is read in.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video