Files.createDirectory():FileAlreadyExistsException [英] Files.createDirectory() : FileAlreadyExistsException

查看:605
本文介绍了Files.createDirectory():FileAlreadyExistsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Java 7的Files类时,我遇到了一个看似奇怪的问题. 根据

I have a seemingly strange issue using Java 7's Files class. I want to make sure my directory and files exist before I start writing to avoid a FileNotFoundException, and according to the Javadocs, createDirectory checks for "the existence of the file and the creation of the directory if it does not exist"

因此,如果它先检查,当目录已经存在时,为什么我的以下代码有问题?

So if it checks first, why do I have a problem with the following code when the directory already exists?

private void writeFile() throws IOException {
    // Make sure parent directory and file are ready
    File file = "mydirectory/my.file";
    File parent = file.getParentFile();
    if (parent != null)
        Files.createDirectory(parent.toPath()); // Why do I get FileAlreadyExistsException? =[
    Files.createFile(file.toPath());

    // Do some file writing stuff!
}

我知道我可以处理一个如果没有文件就创建"的事情,但是我认为这种方法的全部目的就是为我照顾一切!

I know I could just to a 'if not file exists then create' thing, but I thought the whole point of this method was to take care of all that for me!

异常数据:

java.nio.file.FileAlreadyExistsException: mydirectory
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.createDirectory(Unknown Source)
at java.nio.file.Files.createDirectory(Unknown Source)

推荐答案

来自通过首先创建所有不存在的父目录来创建目录.与createDirectory方法不同,如果由于目录已经存在而无法创建该目录,则不会引发异常."

"Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists."

也许您可以使用那个

这篇关于Files.createDirectory():FileAlreadyExistsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆