Skip to content
Advertisement

java.nio.file.NoSuchFileException: why nio not creating file [closed]

I am using java.nio.file package and tried to create file with the following code.

JavaScript

This throws following Exception:

JavaScript

My question is why file is not created?

Please advise

Thanks in anticipation

Advertisement

Answer

Updated Answer:

Now that you’ve shown the full code, there are two major problems:

  1. You’re trying to open the file before ensuring that the directories leading up to it exist, and

  2. You’re using StandardOpenOption.APPEND, but that won’t create a file; it will append to an existing file.

…along with a large number of issues around best practices relative to the number of lines of actual code.

See comments:

JavaScript

But here’s how I would suggest you write it:

JavaScript

…and handle exceptions in the calling layer. Note that, again, because we’re using try-with-resources, the close is automatic (both when there’s an exception and when there isn’t).

Or if you really want to do log-and-continue:

JavaScript

Original Answer:

You haven’t shown the code that’s actually failing, which is a call to newBufferedWriter (this one, or this one). newBufferedWriter takes OpenOptions, the standard set of which are available from StandardOpenOption. Make sure you’ve specified StandardOpenOption.CREATE or StandardOpenOption.CREATE_NEW,

If you use one of those flags, and the code in your question isbefore the newBufferedWriter call, barring some other problem (permissions) it should work:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement