Why is FileWriter not creating a new file ? FileNotFoundException
Asked Answered
S

3

13

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? 
}
Suspect answered 13/8, 2014 at 16:45 Comment(3)
What system are you working on?Chesterchesterfield
Sorry for the noise guys. I had the wrong version. git-pull fixed it.Indeed the problem was with WORKSPACE_PATHSuspect
this should be reopened, this is the first result on google, and the referenced #10767617 problem is permissions, not directory creation. I'd like to add an answer using the Path API.Karelian
N
7

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

File file = new File(WORKSPACE_PATH, fname);
Ness answered 13/8, 2014 at 16:50 Comment(1)
He does mention that opening for appending works fine though?Coercion
B
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();
Burrell answered 13/8, 2014 at 17:0 Comment(4)
And how you know that his WORKSPACE_PATH doesn't contain the separator?Rigsdaler
as he told append works fine that means no problem with the path of the fileStorekeeper
Edited, I forgot to say that you don't need to add one if WORKSPACE_PATH already has one ><Burrell
Or you could use the two-arg form: new File(WORKSPACE_PATH, fname)Carboxylase
C
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);
}
Coercion answered 13/8, 2014 at 16:52 Comment(4)
throws an IOException at that line.Suspect
What is the IOException message details?Coercion
From what I can see, this should be fine - can you print the full WORKSPACE_PATH+fname, and confirm that it is trying to create it in the right place?Coercion
This does essentially what you're trying to do.Coercion

© 2022 - 2024 — McMap. All rights reserved.