Java Files.write NoSuchFileException

ior*_*vic 33 java file-io file filenotfoundexception

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

byte[] contents = project.getCode().getBytes(StandardCharsets.UTF_8);

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

根据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)
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?

Pet*_*rey 50

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

你可以做

Path parentDir = project.getFilePath().getParent();
if (!Files.exists(parentDir))
    Files.createDirectories(parentDir);
Run Code Online (Sandbox Code Playgroud)

  • 如果使用`getParent()`,则永远不会抛出`FileAlreadyExistsException`.父总是一个目录.从文档:"FileAlreadyExistsException - 如果dir存在但不是目录" (2认同)