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

Viewed 91123

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?

10 Answers
//Create New File if not present
if (!file.exists()) {
    file.getParentFile().mkdirs();

    file.createNewFile();
    Log.e(TAG, "File Created");
}

In my case was just a lack of permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Use

yourAppsMainActivityContext.getExternalCacheDir()

instead of

Environment.getExternalStorageDriectory()

to get the file storage path.

Alternatively, you can also try getExternalFilesDir(String type), getExternalCacheDir(), getExternalMediaDirs().

Related