Java Files.write NoSuchFileException

JavaFileFile IoFilenotfoundexception

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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);

Solution 2 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionioreskovicView Question on Stackoverflow
Solution 1 - JavaPeter LawreyView Answer on Stackoverflow
Solution 2 - JavaDeLacView Answer on Stackoverflow