teoREtik
teoREtik

Reputation: 7916

Android: Creating file using createNewFile() method

As described in android documentation, to create a new file which will be situated in the application's directory there is the method in Context class: openFileOutput().

But where will be the file situated if I use simple createNewFile() method from File class.?

Upvotes: 10

Views: 43403

Answers (5)

Sergio
Sergio

Reputation: 30645

Documentation of createNewFile() method says:

Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.

Therefore we don't need to check existence of a file manually:

val dir = context.filesDir.absolutePath + "/someFolder/"
val logFile = File(dir + "log.txt")
try {
    File(dir).mkdirs()     // make sure to call mkdirs() when creating new directory
    logFile.createNewFile()
} catch (e: Exception) {
    e.printStackTrace()
}

Upvotes: 0

cV2
cV2

Reputation: 5319

Somehow createNewFile() was not able to create the complete file path here on my devices.

try {
    if (!futurePhotoFile.exists()) {
        new File(futurePhotoFile.getParent()).mkdirs();
        futurePhotoFile.createNewFile();
    }
} catch (IOException e) {
    Log.e("", "Could not create file.", e);
    Crouton.showText(TaskDetailsActivity.this,
            R.string.msgErrorNoSdCardAvailable, Style.ALERT);
    return;
}

Upvotes: 4

Dominik
Dominik

Reputation: 829

CreateNewFile() is used like this:

File file = new File("data/data/your package name/test.txt");
if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
}

So you will tell the file where it should be created. Remember that you can only create new files on your package. That is "data/data/your package name/".

Upvotes: 34

Nikolay Elenkov
Nikolay Elenkov

Reputation: 52936

Depends on the path you pass to the File constructor. If the parent directory exists, and if you have the permission to write to it, of course.

Upvotes: 0

ngesh
ngesh

Reputation: 13501

it will be stored in the current directory to which your classPath is pointing to

Upvotes: 0

Related Questions