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);
}