12

So I have a code snippet as follows. Im trying to find out why it throws a FileNotFoundException.

File file= new File (WORKSPACE_PATH+fname);
FileWriter fw;
if (file.exists())
{
     fw = new FileWriter(file,true);//if file exists append to file. Works fine.
}
else
{
     fw = new FileWriter(file);// If file does not exist. Create it. This throws a FileNotFoundException. Why? 
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
seeker
  • 6,841
  • 24
  • 64
  • 100
  • What system are you working on? – blueygh2 Aug 13 '14 at 16:48
  • 1
    Sorry for the noise guys. I had the wrong version. `git-pull` fixed it.Indeed the problem was with WORKSPACE_PATH – seeker Aug 13 '14 at 17:04
  • 1
    this should be reopened, this is the first result on google, and the referenced https://stackoverflow.com/questions/10767117/why-filewriter-doesnt-create-a-new-file problem is permissions, not directory creation. I'd like to add an answer using the `Path` API. – xenoterracide Dec 08 '20 at 18:32

3 Answers3

7

Using concatenation when creating the File won't add the necessary path separator.

File file = new File(WORKSPACE_PATH, fname);
nbz
  • 3,806
  • 3
  • 28
  • 56
4

You need to add a separator (Windows : \ and Unix : /, you can use File.separator to get the system's separator) if WORKSPACE_PATH does not have one at its end, and manually creating the file with its parent directories might help.

Try this if WORKSPACE_PATH does not have a separator at its end :

File file = new File(WORKSPACE_PATH + File.separator + fname);

And add this before fw = new FileWriter(file);

file.mkdirs(); // If the directory containing the file and/or its parent(s) does not exist
file.createNewFile();
2

This might work:

File file= new File (WORKSPACE_PATH+fname);
FileWriter fw;
if (file.exists())
{
   fw = new FileWriter(file,true);//if file exists append to file. Works fine.
}
else
{
   file.createNewFile();
   fw = new FileWriter(file);
}
roelofs
  • 2,132
  • 20
  • 25