Skip to content Skip to sidebar Skip to footer

Android Write To File Permission Denied

I'm trying to write to a file in android but i keep getting this error: java.io.FileNotFoundException: /storage/emulated/0/Notes/TestFile.txt (Permission denied) Searching this si

Solution 1:

You have mentioned permission in AndroidManifest.xml but not yet granted it from the user. You need to grant WRITE_EXTERNAL_STORAGE permission through the user in your Android activity.

if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, newString[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }

Next time you launch the Activity, grant it the permission and then you can access external storage. Mind that this will give only write access, not read access.

Solution 2:

Fixed it, i had to request permission using this code just above where i wrote to the file:

            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    1);

            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    1);

The full code looks like this to write to a file in a button click function:

          ActivityCompat.requestPermissions(MainActivity.this,
                    newString[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    1);

            ActivityCompat.requestPermissions(MainActivity.this,
                    newString[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    1);




            try {
                Fileroot=newFile(Environment.getExternalStorageDirectory(), "Notes");
                if (!root.exists()) {
                    root.mkdirs();
                }
                Filegpxfile=newFile(root, "TestFile.txt");
                FileWriterwriter=newFileWriter(gpxfile);
                writer.append("Hello World");
                writer.flush();
                writer.close();
                Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
            }

Post a Comment for "Android Write To File Permission Denied"