10

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.?

5 Answers 5

34

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/".

Sign up to request clarification or add additional context in comments.

Comments

4

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;
}

Comments

0

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

Comments

0

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.

Comments

0

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()
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.