1

I'm trying to implement object serialization in java. I'm not sure why my code is currently leading to an EOFException, as my code is writing to the file it's supposed to:

Currently, my code is:

import java.io.*;

public class main {
    public static void main(String[] args) {
        product p1 = new product("product", 0, "this is a product.");
        
        ObjectOutputStream out = null;
        
        try {
            out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("info.dat")));
            out.writeObject(p1);
            out.writeObject(p1);
            System.out.println("Wrote to file");
        } catch (FileNotFoundException e) {
            System.out.println("");
        } catch (IOException e) {
            System.out.println("");
        }
        
        ObjectInputStream in = null;
        
        try {
            in = new ObjectInputStream(
                    new BufferedInputStream(
                            new FileInputStream("info.dat")));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    
        
        
    }
}

while product class is extremely simple, being only:

import java.io.Serializable;

public class product implements Serializable {
    String name;
    double cost;
    String description;
    
    public product(String a,double b,String c) {
        name = a;
        cost = b;
        description = c;
    }
    
}

Currently, the output is enter image description here

Meaning that my code did run and did write to file. I also added an extra write object just in case, so I really don't understand how an EOF error is occurring. Can somebody please explain why?

Ryan Fu
  • 349
  • 1
  • 5
  • 22
  • 1
    does this answer your question https://stackoverflow.com/questions/664331/when-will-an-eofexception-occur-in-javas-streams – ali varaste pour Dec 12 '21 at 06:48
  • 2
    You must close your `out` for changes to be written to disk to the underlying `FileOutputStream`. – vanOekel Dec 12 '21 at 11:59
  • @vanOekel could you please explain why this is? – Ryan Fu Dec 12 '21 at 17:43
  • 1
    There are several reasons, but the main one here is that [`close`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/FilterOutputStream.html#close()) calls [`flush`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/BufferedOutputStream.html#flush()). In general: always close your `in`/`outputstream`s and do it as soon as possible to avoid trouble. – vanOekel Dec 12 '21 at 21:03

0 Answers0