The File
class in Java contain methods that utilize boolean values to indicate the successfulness of the operation being carried out. Users of said methods are required to check the return value every time it is being called.
Below is the snippet of the documentations taken from mkdir()
stating the requirement:
public boolean mkdir()
Creates the directory named by this file, assuming its parents exist. Use mkdirs if you also want to create missing parents.
Note that this method does not throw IOException on failure. Callers must check the return value.
There's also a case with createNewFile()
which (even weirder) use both boolean values as well as thrown exceptions to indicate successfulness:
public boolean createNewFile() throws IOException
Creates a new, empty file on the file system according to the path information stored in this file. This method returns true if it creates a file, false if the file already existed. Note that it returns false even if the file is not a file (because it's a directory, say).
...
Note that this method does not throw IOException if the file already exists, even if it's not a regular file. Callers should always check the return value, and may additionally want to call isFile.
Now, this seems inconvenient at best, because the user would have to anticipate two kind of error scenarios instead of just using a simple try-catch
block.
What's the reason behind this fuss?
Because that's the way they designed it, over twenty years ago. If you can get the developers out of their retirement homes and off their Zimmer frames you might get a better answer. Otherwise we are all just guessing.
However you don't need to call these methods as often as some people here seem to think. For example, isFile()/exists()/delete()/createNewFile()
are all redundant before new FileInputStream(...)
or new FileOutputStream(...)
, which will throw exactly the exceptions you are looking for. Calling File.exists()/delete()/createNewFile()
before either of these or the corresponding FileReader/Writer
constructors is worse than useless, it is a positive waste of time and space, doing work that the constructor (or rather the operating system code invoked by the constructor) has to repeat. I doubt that I have ever used File.createNewFile()
in 20 years.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With