我有一个看似奇怪的问题,使用Java 7的Files
类。 我想确保我的目录和存在的文件之前,我开始写,以避免FileNotFoundException
,并根据Javadocs,createDirectory
检查“文件的存在和目录的创建,如果它不存在”Files.createDirectory():FileAlreadyExistsException
因此,如果它首先检查,为什么当目录已经存在时,下面的代码有问题?
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)
你可以发布异常吗?并告诉我它抛出哪一行? – Dima 2013-04-23 21:05:45