我正在尝试使用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(); –