Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileNotFoundException (The system cannot find the path specified)

Tags:

java

file-io

I get this exception:

java.io.FileNotFoundException: C:\...\filename.xml (The system cannot find the path specified)

using this code:

FileWriter fileWriter = new FileWriter(new File(path + date + time "filename.xml"));
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write("data");

Path exists but directories for 'date' and 'time' need to be created. Application has full permissions on the directory.

Any ideas?

like image 279
Michael Avatar asked Dec 13 '10 13:12

Michael


People also ask

Why am I getting a FileNotFoundException?

This exception is thrown during a failed attempt to open the file denoted by a specified pathname. Also, this exception can be thrown when an application tries to open a file for writing, but the file is read-only, or the permissions of the file do not allow the file to be read by any application.

What is java IO FileNotFoundException?

java.io.FileNotFoundException. Signals that an attempt to open the file denoted by a specified pathname has failed. This exception will be thrown by the FileInputStream , FileOutputStream , and RandomAccessFile constructors when a file with the specified pathname does not exist.

Can we handle FileNotFoundException?

FileNotFoundException occurs at runtime so it is a checked exception, we can handle this exception by java code, and we have to take care of the code so that this exception doesn't occur.


3 Answers

The problem is because I'm creating a subdirectory in which to write the files. So I currently have C:\example\ and want to write my files in C:\example\<date>\<time>\<files>

You need to call File#mkdirs() before writing.

File file = new File("C:/example/newdir/newdir/filename.ext");
file.mkdirs();
// ...
like image 72
BalusC Avatar answered Sep 24 '22 13:09

BalusC


Do assume that the computer is right and you are wrong.

And, in that scenario, the directory to which you want to write does not exit (or does not have permissions to do so).

  1. check the current working dir System.getProperty("user.dir")
  2. debug from there
like image 42
Frankie Avatar answered Sep 25 '22 13:09

Frankie


Code works for me. (Need to add a writer.close() for text to show up in the file.)

like image 20
jzd Avatar answered Sep 22 '22 13:09

jzd