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.
还有一个createNewFile()的情况(甚至更奇怪)使用布尔值和抛出异常来表示成功:
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.
现在,这看起来很不方便,因为用户必须预测两种错误情况,而不是仅使用简单的try-catch块.
这个大惊小怪的原因是什么?
解决方法
但是,您不需要经常调用这些方法,因为这里的某些人似乎在想.例如,isFile()/ exists()/ delete()/ createNewFile()在新的FileInputStream(…)或新的FileOutputStream(…)之前都是冗余的,这将完全抛出您要查找的异常.在其中任何一个或相应的FileReader / Writer构造函数之前调用File.exists()/ delete()/ createNewFile()比无用更糟糕,这是对时间和空间的积极浪费,做构造函数的工作(或者更确切地说是操作系统代码调用的系统代码)必须重复.我怀疑我20年来曾经使用过File.createNewFile().