我正在尝试使用Files.write()方法将一些文本写入文件。
byte[] contents = project.getCode().getBytes(StandardCharsets.UTF_8);
try {
Files.write(project.getFilePath(), contents, StandardOpenOption.CREATE);
} catch (IOException ex) {
ex.printStackTrace();
return;
}根据该接口,如果该文件不存在,则会创建该文件并将其写入。
然而,我得到了这样的结论:
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)我是不是遗漏了什么?
发布于 2013-01-11 01:28:45
您应该能够创建文件,但不能创建目录。您可能需要先检查目录C:\Users\Administrator\Desktop\work是否存在。
你可以做到
Path parentDir = project.getFilePath().getParent();
if (!Files.exists(parentDir))
Files.createDirectories(parentDir);发布于 2013-01-11 01:32:57
如果使用默认的OpenOptions参数,则会写入文件。如果指定CREATE,则不使用默认参数,但仅使用CREATE。尝试在CREATE之外添加WRITE,或者只将该参数保留为空
https://stackoverflow.com/questions/14263725
复制相似问题