gpt4 book ai didi

Java Files.write NoSuchFileException

转载 作者:IT老高 更新时间:2023-10-28 21:05:47 32 4
gpt4 key购买 nike

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

我错过了什么吗?

最佳答案

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

你可以的

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

关于Java Files.write NoSuchFileException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14263725/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com