3

The File class lets you create new directories and new files on a file system.

The methods to accomplish this are:

public boolean createNewFile() throws IOException
-and-
public boolean mkdir()

How does the operation of creating a new file potentially lead to an IOException being thrown but the operation of creating a new directory does not?

I'm trained as a Java developer to be very aware of operations that throw checked exceptions, so I would be expecting more consistency here unless there was a very good reason for the lack of consistency. Both methods return true if the operation succeeded.

4

2 回答 2

4

因为它是API的一部分:

public boolean mkdir()

创建由此抽象路径名命名的目录。

返回:
true当且仅当目录被创建时;false否则

我会接受在这方面可以改进 API。

于 2013-08-20T09:26:01.480 回答
2

我们只能猜测,但我的猜测是,主要原因是他们学会了。

createNewFile()是在 Java 1.2 中添加的,比 Java 1.0 晚了几年。从那以后,他们了解到使用返回值是传达错误条件的一种不好的方式(他们以前知道这一点,但并没有在任何地方都应用它)。

请注意,当createNewFile()无异常存在时,则请求的文件存在!返回值的唯一区别是它之前是否存在。

如果创建文件失败,则抛出异常。

于 2013-08-20T11:33:26.127 回答