Question

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

Was it helpful?

Solution

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top