简体   繁体   English

File.mkdir不会抛出IOException但File.createNewFile会抛出IOException

[英]File.mkdir doesn't throw IOException but File.createNewFile does

The File class lets you create new directories and new files on a file system. File类允许您在文件系统上创建新目录和新文件。

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? 如何创建新文件的操作可能会导致抛出IOException但是创建新目录的操作不会?

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. 我接受过Java开发人员的培训,非常了解抛出检查异常的操作,所以我希望这里有更多的一致性,除非有充分的理由导致缺乏一致性。 Both methods return true if the operation succeeded. 如果操作成功,则两个方法都返回true。

Because it's part of the API : 因为它是API的一部分:

 public boolean mkdir() 

Creates the directory named by this abstract pathname. 创建此抽象路径名指定的目录。

Returns: 返回:
true if and only if the directory was created; 当且仅当目录已创建时才为true ; false otherwise 否则是false

I would accept that the API could be improved in this respect. 我会接受在这方面可以改进API。

We can only guess, but my guess is that the main reason is that they learned. 我们只能猜测,但我的猜测是,主要原因是他们学到了。

createNewFile() was added in Java 1.2, which is several years after Java 1.0. createNewFile()是在Java 1.2中添加的,这是Java 1.0之后的几年。 And they have since learned that using return values are a bad way to communicate error conditions (they knew it before, but didn't apply it everywhere). 而且他们已经知道使用返回值是一种沟通错误条件的坏方法(他们以前知道它,但并未在任何地方应用它)。

Note that when createNewFile() exists without an exception, then the requested file exists! 请注意,当createNewFile()存在而没有异常时,则所请求的文件存在! The only distinction made by the return value is whether or not it existed before. 返回值唯一的区别在于它之前是否存在。

If it fails to create the file, then an exception is thrown. 如果无法创建文件,则抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM