Java Files.write NoSuchFileException

ioreskovic picture ioreskovic · Jan 10, 2013 · Viewed 53.3k times · Source

I'm trying to write some text to a file using Files.write() method.

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

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

According to the API, if the file doesn't exist, it will be created and then written to.

However, I get this:

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)

Am I missing something?

Answer

Peter Lawrey picture Peter Lawrey · Jan 10, 2013

You should be able to create a file, but you can't create a directory. You may need to check the directory C:\Users\Administrator\Desktop\work exists first.

You can do

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