57

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?

3
  • 7
    Does directory C:\Users\Administrator\Desktop\work exist? (and why do you develop as an admin?) Commented Jan 10, 2013 at 17:28
  • 1
    use file.getParentFile().mkdirs(); Commented Jan 10, 2013 at 17:32
  • 1
    Yes, I'm stupid. I forgot to check if the folder exists :D Commented Jan 10, 2013 at 17:39

2 Answers 2

75

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);
Sign up to request clarification or add additional context in comments.

3 Comments

@AlikElzin-kilaka if you don't, you can get a FileAlreadyExistsException
If getParent() is used, FileAlreadyExistsException will never be thrown. Parent is always a directory. From the documentation: "FileAlreadyExistsException - if dir exists but is not a directory"
flawless answer Peter!
1

The file will be written if default OpenOptions parameter is used. If you specify CREATE, default parameters will not be used, but it is used just CREATE. Try to add WRITE in addition to CREATE, or just leave that parameter empty

1 Comment

wrong. Files.write will add WRITE regardless of any options given. see java.nio.file.spi.FileSystemProvider.newOutputStream source

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.