首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java Files.write NoSuchFileException

Java Files.write NoSuchFileException
EN

Stack Overflow用户
提问于 2013-01-11 01:26:47
回答 2查看 55.5K关注 0票数 47

我正在尝试使用Files.write()方法将一些文本写入文件。

代码语言:javascript
复制
byte[] contents = project.getCode().getBytes(StandardCharsets.UTF_8);

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

根据该接口,如果该文件不存在,则会创建该文件并将其写入。

然而,我得到了这样的结论:

代码语言:javascript
复制
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)

我是不是遗漏了什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-01-11 01:28:45

您应该能够创建文件,但不能创建目录。您可能需要先检查目录C:\Users\Administrator\Desktop\work是否存在。

你可以做到

代码语言:javascript
复制
Path parentDir = project.getFilePath().getParent();
if (!Files.exists(parentDir))
    Files.createDirectories(parentDir);
票数 67
EN

Stack Overflow用户

发布于 2013-01-11 01:32:57

如果使用默认的OpenOptions参数,则会写入文件。如果指定CREATE,则不使用默认参数,但仅使用CREATE。尝试在CREATE之外添加WRITE,或者只将该参数保留为空

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14263725

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档