【发布时间】:2013-04-23 21:01:29
【问题描述】:
我在使用 Java 7 的 Files 类时遇到了一个看似奇怪的问题。
我想在开始写作之前确保我的目录和文件存在以避免FileNotFoundException,并根据Javadocs,createDirectory 检查“文件是否存在,如果不存在则创建目录存在”
那么如果它先检查,为什么在目录已经存在的情况下我下面的代码会有问题?
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!
}
我知道我可以只做一个“如果文件不存在则创建”的事情,但我认为这种方法的重点是为我处理所有这些!
异常数据:
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)
【问题讨论】:
-
你能发布异常吗?并告诉我它抛出了哪条线?