我有一個看似奇怪的問題,使用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