Iv been trying to write a java program to read an image from a list of images in a file I.E:

  • File
  • Filename
  • Image1
  • Filename
  • Image2
  • Filename
  • Image3

The problem i am having is that the filename's are string objects followed by an image. So i was wondering if anyone could point me in the right direction to read the file i have written.

public class imageloader {
    String name;
    BufferedImage image;

    public imageloader(String url) 
        try {

            FileInputStream saveFile = new FileInputStream(url);

            try {

                ObjectInputStream restore = new ObjectInputStream(saveFile);
                this.name = (String) restore.readObject();
                this.image = ImageIO.read(restore);


            } catch (IOException e) {

            } catch (ClassNotFoundException e) {


        } catch (FileNotFoundException e) {




This is how i am how i am saving the file

            FileOutputStream saveFile=new FileOutputStream("testfile");
            ObjectOutputStream save = new ObjectOutputStream(saveFile);
            // Now we do the save.
            ImageIO.write(image, "png", saveFile);
            // Close the file.
            save.close(); // This also closes saveFile.

Currently it throws no errors, but does not seem to actually read the data back into the buffered image. Any Ideas?

5 Years
Discussion Span
Last Post by vishalonne

You can't mix object I/O and imageIO in a single file like that. ImageIO writes a single image in the desired format (jpg, png etc). The API doc also says " If there is already a File present, its contents are discarded.", so it's stricly one image per file. ObjectStreams support multiple objects in one file, but they have their own special format to do that. Unfortunately BufferedImages are not Serialisable, so you can't write then to an Object stream.
One possible solution is to convert you Image objects to ImageIcon (and v.v after reading them). ImageIcons can be written to /read from Object streams with writeObject and readObject, and you can have as many as you want, mixed with any other objects, in a single file.

Edited by JamesCherrill


thanks, thats what i thought when i tried it originally and found it not to be serializeable. Quite annoying but ill try the image icon thing thanks!


I have done something like what you want, I reading image file then converting them in binary format for storing them in MySQL. Then next part is reading those image from Mysql database and reformat those binary data in imgae format back. I use image icon. you can check this http://cbsecsnip.in tutorial section. May this help you

Edited by vishalonne

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.