2013-01-10 50 views
23

我正在嘗試使用Files.write()方法將一些文本寫入文件。Java Files.write NoSuchFileException

byte[] contents = project.getCode().getBytes(StandardCharsets.UTF_8); 

try { 
    Files.write(project.getFilePath(), contents, StandardOpenOption.CREATE); 
} catch (IOException ex) { 
    ex.printStackTrace(); 
    return; 
} 

根據API,如果該文件不存在,它將被創建並寫入。

不過,我得到這個:

java.nio.file.NoSuchFileException: C:\Users\Administrator\Desktop\work\Default.txt 
    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.newByteChannel(Unknown Source) 
    at java.nio.file.spi.FileSystemProvider.newOutputStream(Unknown Source) 
    at java.nio.file.Files.newOutputStream(Unknown Source) 
    at java.nio.file.Files.write(Unknown Source) 

我這麼想嗎?

+7

是否存在目錄'C:\ Users \ Administrator \ Desktop \ work'? (爲什麼你作爲管理員開發?) – fge

+5

文件夾是否丟失? –

+1

使用file.getParentFile()。mkdirs(); –

回答

35

你應該可以創建一個文件,但是你不能創建一個目錄。您可能需要先檢查目錄C:\Users\Administrator\Desktop\work

你可以做,如果使用默認參數OpenOptions

Path parentDir = project.getFilePath().getParent(); 
if (!Files.exists(parentDir)) 
    Files.createDirectories(parentDir); 
+1

爲什麼檢查是否已經存在? –

+0

@ AlikElzin-kilaka如果你不這樣做,你可以得到'FileAlreadyExistsException' –

+1

如果使用'getParent()','FileAlreadyExistsException'永遠不會被拋出。父始終是一個目錄。從文檔:「FileAlreadyExistsException - 如果目錄存在但不是目錄」 –

1

文件將被寫入。如果您指定CREATE,則不會使用默認參數,但它僅用於CREATE。嘗試添加寫入除了CREATE,或只是保留該參數爲空

+4

錯誤。無論給出什麼選項,Files.write都會添加「WRITE」。請參閱'java.nio.file.spi.FileSystemProvider.newOutputStream'源文件 – lyomi

+1

它爲我工作!對不起,給你一個減號。 – Desik

相關問題