java.io.FileNotFoundException: /storage/emulated/0/Notes/fact50Result.txt: open failed ENOENT (No such file or directory)

I am trying to export the results of a factorial calculation in a txt file. I found this code that looked quite straight forward from this article here. However I’m getting the error on the title. What am I doing wrong?

I have typed this into the manifest:

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

And this is my code related to saving:

    public void save(View v) {
     if(numOnRAM!=-1) {
         EditText text = (EditText) findViewById(R.id.resultTextBox);
         String data = text.getText().toString();
         generateNoteOnSD(this,"fact"+numOnRAM+"Results.txt", data);
     }
}

public void generateNoteOnSD(Context context, String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "Notes");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(context, "File "+sFileName+" saving success!", Toast.LENGTH_LONG).show();

    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();//After adding this 
//toast message did I realise the error thar occurs.

    }
}

Answer

As discussed in the comments, you need to request permissions at runtime to allow your app to write to external storage. You can check if your app has the permission already by using checkSelfPermission(). For example:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
    // Do the file write
} else {
    // Request permission from the user
    ActivityCompat.requestPermissions(this, 
            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
    ...
}

In order to handle this permission request, you’ll also need to implement onRequestPermissionsResult() from OnRequestPermissionsResultCallback, for example:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case 0:
            // Re-attempt file write
    }
}

Read the documentation for full information.

Leave a Reply

Your email address will not be published. Required fields are marked *