加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 有没有理由为什么File中的某些方法使用布尔值来表示它的

发布时间:2020-12-14 05:52:39 所属栏目:Java 来源:网络整理
导读:Java中的File类包含使用布尔值来指示正在执行的操作的成功的方法.所述方法的用户需要在每次调用时检查返回值. 以下是从mkdir()获取的文档摘要,说明了要求: public boolean mkdir() Creates the directory named by this file,assuming its parents exist. U
Java中的File类包含使用布尔值来指示正在执行的操作的成功的方法.所述方法的用户需要在每次调用时检查返回值.

以下是从mkdir()获取的文档摘要,说明了要求:

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块.

这个大惊小怪的原因是什么?

解决方法

因为这是他们设计它的方式,二十多年前.如果您可以让开发人员离开他们的养老院并离开Zimmer框架,您可能会得到更好的答案.否则我们都只是在猜测.

但是,您不需要经常调用这些方法,因为这里的某些人似乎在想.例如,isFile()/ exists()/ delete()/ createNewFile()在新的FileInputStream(…)或新的FileOutputStream(…)之前都是冗余的,这将完全抛出您要查找的异常.在其中任何一个或相应的FileReader / Writer构造函数之前调用File.exists()/ delete()/ createNewFile()比无用更糟糕,这是对时间和空间的积极浪费,做构造函数的工作(或者更确切地说是操作系统代码调用的系统代码)必须重复.我怀疑我20年来曾经使用过File.createNewFile().

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读