Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.createNewFile() thowing IOException No such file or directory

Tags:

java

file-io

I have a method that writes to a log file. If the file exists it should append to it, if not then I want it to create a new file.

if (!file.exists() && !file.createNewFile()) {     System.err.println("Error with output file: " + outFile         + "\nCannot create new file.");     continue; } 

I have that to check that a file can be created. file is a java.io.File object. createNewFile is throwing an IOException: No such file or directory. This method has been working perfectly since I wrote it a few weeks ago and has only recently starting doing this although I don't know what I could have changed. I have checked, the directory exists and I have write permissions for it, but then I thought it should just return false if it can't make the file for any reason.

Is there anything that I am missing to get this working?

like image 325
A Jackson Avatar asked Oct 06 '09 11:10

A Jackson


People also ask

Why can't I create a directory with isfile?

File.isFile () is false if the file / directory does not exist, so you can't use it to test whether you're trying to create a directory. But that's not the first issue here.

What happens if createnewfile throws an exception?

If createNewFile throws an exception then it's safe to assume that you either wanted that file to be created (it wasn't -> bad) or you wanted to later write to it (will result in an exception -> bad). In any case it's good to fail fast and let the caller decide how to procede.

What is the use of createnewfile in Java?

The createNewFile () function is a part of File class in Java . This function creates new empty file. The function returns true if the abstract file path does not exist and a new file is created. It returns false if the filename already exists.

What is the return type of createnewfile () function?

Return Type: The function returns boolean data type representing whether the new file is created or not. Exception: This method throws following exceptions: Below programs illustrates the use of createNewFile () function: Example 1: The file “F:\program1.txt” does not exist Example 2: The file “F:\program.txt” is a existing file in F: Directory.


2 Answers

try to ensure the parent directory exists with:

file.getParentFile().mkdirs() 
like image 81
Omry Yadan Avatar answered Oct 01 '22 12:10

Omry Yadan


Perhaps the directory the file is being created in doesn't exist?

like image 38
Miserable Variable Avatar answered Oct 01 '22 10:10

Miserable Variable