CJx*_*JxD 9 java file-io java-7
使用Java 7的Files
类我有一个看似奇怪的问题.我想在开始编写之前确保我的目录和文件存在以避免a 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!
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以只是'如果不存在文件然后创建'的事情,但我认为这个方法的重点是为我照顾所有这些!
例外数据:
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)
Run Code Online (Sandbox Code Playgroud)
Mat*_*ter 21
从文档中
public static Path createDirectories(Path dir, FileAttribute<?>... attrs) throws IOException
Run Code Online (Sandbox Code Playgroud)
"首先通过创建所有不存在的父目录来创建目录.与createDirectory方法不同,如果由于目录已经存在而无法创建目录,则不会引发异常."
也许你可以使用那个