如果不存在,则清理 Java 7 创建文件的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27877924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:12:39  来源:igfitidea点击:

Clean Java 7 way to create file if not exists

javafile-ionio

提问by emotionull

What is the Java 7 or Java 8 way to create a file if that does not exists?

如果不存在,Java 7 或 Java 8 创建文件的方法是什么?

采纳答案by fge

Not sure what you want, but for instance:

不确定你想要什么,但例如:

try {
    Files.createFile(thePath);
} catch (FileAlreadyExistsException ignored) {
}

And there are other solutions; for instance:

还有其他解决方案;例如:

if (!Files.exists(thePath, LinkOption.NOFOLLOW_LINKS))
    Files.createFile(thePath);

Note that unlike File, these will throw exceptions if file creation fails! And relevant ones at that (for instance, AccessDeniedException, ReadOnlyFileSystemException, etc etc)

请注意,与 不同的是File,如果文件创建失败,这些将抛出异常!而相关的多个在那(例如AccessDeniedExceptionReadOnlyFileSystemException,等等等等)

See herefor more information. Also see why you should migrate to java.nio.file, quickly.

请参阅此处了解更多信息。还要了解为什么您应该java.nio.file快速迁移到

回答by Aniket Thakur

You can do

你可以做

File f = new File("pathToYourFile");
if(!f.exists() && !f.isDirectory())
{
    f.createNewFile()
}

If you want to use NIO.2 you can use methods Files class.

如果你想使用 NIO.2 你可以使用方法 Files 类。

boolean exists(Path path,LinkOption. . . options)
Path createTempFile(Path dir, String prefix,String suffix, FileAttribute<?>. . . attrs)
createFile(Path path, FileAttribute<?>... attrs)

As fge has mentioned in the comments createNewFile()methods returns booleanvalue denoting if file was actually created or not. Unfortunately there is no way to know why it failed. In fact this is one of the reason NIO.2 I/O APIs were introduced.

正如 fge 在评论中提到的createNewFile()方法返回boolean值表示文件是否实际创建。不幸的是,没有办法知道它为什么失败。事实上,这是引入 NIO.2 I/O API 的原因之一。