我正在嘗試使用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)
我這麼想嗎?
是否存在目錄'C:\ Users \ Administrator \ Desktop \ work'? (爲什麼你作爲管理員開發?) – fge
文件夾是否丟失? –
使用file.getParentFile()。mkdirs(); –