Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Files.write NoSuchFileException

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?

like image 938
ioreskovic Avatar asked Jan 10 '13 17:01

ioreskovic


People also ask

How do I resolve Java NIO file NoSuchFileException?

The problem is that the file is not on your classpath, hence when you run your program, Java can't find the file. One workaround would be to just use the fully qualified path to the file, e.g. C:\your_folder\project\result. csv . The alternative is to load it from the classpath.

What is no such file exception?

Class NoSuchFileExceptionChecked exception thrown when an attempt is made to access a file that does not exist.

What is Nio file in Java?

Java For Testers Java NIO package provide one more utility API named as Files which is basically used for manipulating files and directories using its static methods which mostly works on Path object.


1 Answers

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); 
like image 112
Peter Lawrey Avatar answered Sep 18 '22 17:09

Peter Lawrey