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?
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.
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.
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.
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.
try to ensure the parent directory exists with:
file.getParentFile().mkdirs()
Perhaps the directory the file is being created in doesn't exist?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With