【问题标题】:Java Files.write NoSuchFileExceptionJava Files.write NoSuchFileException
【发布时间】:2012-12-25 04:23:25
【问题描述】:

我正在尝试使用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 是否存在? (以及你为什么要以管理员的身份发展?)
  • 使用 file.getParentFile().mkdirs();
  • 是的,我很愚蠢。我忘了检查文件夹是否存在:D

标签: java file file-io filenotfoundexception


【解决方案1】:

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

你可以的

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

【讨论】:

  • @AlikElzin-kilaka 如果你不这样做,你可以得到一个FileAlreadyExistsException
  • 如果使用getParent(),则永远不会抛出FileAlreadyExistsException。父级始终是一个目录。来自文档:“FileAlreadyExistsException - 如果 dir 存在但不是目录”
  • 完美回答彼得!
【解决方案2】:

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

【讨论】:

  • 错误。 Files.write 将添加WRITE,无论给出任何选项。见java.nio.file.spi.FileSystemProvider.newOutputStream
猜你喜欢
  • 2017-02-24
  • 2013-11-29
  • 2021-09-02
  • 1970-01-01
  • 2017-12-12
  • 2017-10-14
  • 1970-01-01
  • 2020-02-04
  • 2015-02-10
相关资源
最近更新 更多