我在使用 Java 7 时遇到了一个看似奇怪的问题Files
班级。
我想在开始编写之前确保我的目录和文件存在,以避免FileNotFoundException
,并根据Javadocs http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createDirectory%28java.nio.file.Path,%20java.nio.file.attribute.FileAttribute...%29, 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)
来自文档 http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createDirectories%28java.nio.file.Path,%20java.nio.file.attribute.FileAttribute...%29
public static Path createDirectories(Path dir, FileAttribute<?>... attrs) throws IOException
“通过首先创建所有不存在的父目录来创建目录。与 createDirectory 方法不同,如果目录因已存在而无法创建,则不会引发异常。”
也许你可以用那个
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)