Clean Java 7 种创建文件的方法(如果不存在)

Clean Java 7 way to create file if not exists

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

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

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

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

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

请注意,与 File 不同,如果文件创建失败,它们将抛出异常!以及相关的(例如,AccessDeniedExceptionReadOnlyFileSystemException 等)

here for more information. Also see why you should migrate to java.nio.file, quickly

你可以做到

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

如果你想使用 NIO.2,你可以使用方法文件 class。

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

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