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

Clean Java 7创建文件的方法(如果不存在),java,file-io,nio,Java,File Io,Nio,如果文件不存在,Java 7或Java 8创建文件的方法是什么?不确定您想要什么,但例如: try { Files.createFile(thePath); } catch (FileAlreadyExistsException ignored) { } if (!Files.exists(thePath, LinkOption.NOFOLLOW_LINKS)) Files.createFile(thePath); 还有其他解决办法;例如: try { Files.c

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

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

try {
    Files.createFile(thePath);
} catch (FileAlreadyExistsException ignored) {
}
if (!Files.exists(thePath, LinkOption.NOFOLLOW_LINKS))
    Files.createFile(thePath);
还有其他解决办法;例如:

try {
    Files.createFile(thePath);
} catch (FileAlreadyExistsException ignored) {
}
if (!Files.exists(thePath, LinkOption.NOFOLLOW_LINKS))
    Files.createFile(thePath);
请注意,与文件不同,如果文件创建失败,它们将抛出异常!以及相关的异常(例如,
AccessDeniedException
ReadOnlyFileSystemException
,等等)

有关更多信息,请参阅。另请参见。

您可以这样做

File f = new File("pathToYourFile");
if(!f.exists() && !f.isDirectory())
{
    f.createNewFile()
}
如果您想使用NIO.2,您可以使用类文件的方法

boolean exists(Path path,LinkOption. . . options)
Path createTempFile(Path dir, String prefix,String suffix, FileAttribute<?>. . . attrs)
createFile(Path path, FileAttribute<?>... attrs)
存在布尔值(路径、链接选项…选项) 路径createTempFile(路径目录、字符串前缀、字符串后缀、文件属性…属性) createFile(路径、文件属性…属性)
正如fge在注释
createNewFile()
中所提到的,方法返回
布尔值
值,指示文件是否实际创建。不幸的是,没有办法知道它失败的原因。事实上,这就是引入NIO.2I/OAPI的原因之一

AFAIK Java 8并没有改变我们处理文件的方式。@alfasin Java 7(因此Java 8)用Java.nio.file极大地改变了它;而今天,不幸的是,它仍然是underused@fge确实如此。我会删除它。可能是重复的。@Joe正如我在前面的评论中所说,这个问题没有提供任何java.nio.file的解决方案。这是2015年!更重要的是,这个问题明确提到了Java7+。。。您没有检查
.createNewFile()的结果。
!所以没有一行代码可以做到这一点?没有,但这真的很重要吗?;)如果需要,您可以创建自己的实用程序方法,这实际上不是问题,请尝试{Files.createFile(thePath);}catch(filealreadyexistexception被忽略){}