Java Files.write NoSuchFileException

54

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

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
1
使用 file.getParentFile().mkdirs(); - İsmet Alkan
1
是的,我很傻。我忘记检查文件夹是否存在:D - ioreskovic
2个回答

72

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

您可以这样做:

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

如果你不这样做,就会得到一个FileAlreadyExistsException异常。 - Peter Lawrey
2
如果使用getParent(),则永远不会抛出FileAlreadyExistsException。父目录始终是一个目录。根据文档:“如果dir存在但不是目录,则会抛出FileAlreadyExistsException”。 - AlikElzin-kilaka
1
完美的回答,Peter! - Gaurav

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

5
“Files.write”会忽略任何给定的选项并添加“WRITE”。请参阅“java.nio.file.spi.FileSystemProvider.newOutputStream”源代码。 - lyomi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接