0
public void save() throws IOException {
            File f = new File(path);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }
            FileOutputStream fout = new FileOutputStream(f, false);//overwrite, append set to false
            ObjectOutputStream out = new ObjectOutputStream(fout);

            out.writeObject(this.vehicles);
            out.close();
        }

I Have the following code that saves an object of type vehicule into a file. However, I don't understand quite well how it works since it was a sample provided for me, and since I am new in the java field.

I am wondering what is the interpretation of these lines if (!f.getParentFile().exists()) { f.getParentFile().mkdirs(); } I am wondering what getParentFile().exists() does and why are we searching for the parent file while we are interested in the file itself. same question for the next line: why are we interested in the parent directory when we are going to create the file? I would like to know also the difference between FileOutputStream and ObjectOutputStream and why both are used one next to another in the following lines FileOutputStream fout = new FileOutputStream(f, false);//overwrite, append set to false ObjectOutputStream out = new ObjectOutputStream(fout); Thank you in advance

user1680944
  • 537
  • 2
  • 13
  • 23

1 Answers1

2

Files are pointers to file or directory locations on a File System. If you intend to write to a file, though, the parent directory in which it will reside must exist. Otherwise, you'll get an IOException. The mkdirs call will create the necessary parent directory (or directories) to avoid that IOException.

I don't think the exists check is really necessary, though, since the mkdirs method returns false if it actually didn't create anything.

Also, you should close your OutputStream within a finally block or use the Java 7 try-with-resources:

try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f, false))) {
    out.writeObject(vehicles);
}
bdkosher
  • 5,753
  • 2
  • 33
  • 40
  • You should keep the `exists`, but also check the return value of `mkdirs` to handle the case where you don't have permission to create the parent directory. – Alvin Thompson Apr 27 '13 at 13:20
  • 1
    Very good advice about always closing everything/releasing resources in a `finally`. If you're using JDK 7+, you can also use the "try with resources" construct which does the same thing but is much cleaner and provides the ability to get at "swallowed" exceptions. – Alvin Thompson Apr 27 '13 at 13:22
  • Good point, Alvin. Updated the answer with the try-with-resources approach. – bdkosher Apr 27 '13 at 14:35