Getting a Permission denied error when creating a

2019-09-17 13:53发布

问题:

I have this in my manifest:

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

This is where I am trying to create and write to a file (it is in a file called EnterUserInfo.java:

// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};


/**
 * Checks if the app has permission to write to device storage
 *
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        System.out.println("INSIDEEEEEE");
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    } else {
        System.out.println("HEREEEEEEEEE");
    }
}

private void writeToFile(String data, Context context) {

    verifyStoragePermissions(this);
    String FILENAME = "new_clients.txt";
    String string = "hello world!";

    try {
        FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
        fos.write(string.getBytes());
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


    try {
        FileOutputStream fos = context.openFileOutput("new_clients.txt", Context.MODE_PRIVATE);
        fos.write(data.getBytes());
        fos.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

When I try to create a file, this is what appears:

I/System.out: HEREEEEEEEEE
W/ContextImpl: Failed to ensure /data/user/0/c.b.project/files: mkdir failed: EACCES (Permission denied)
W/FileUtils: Failed to chmod(/data/user/0/cs.b07.cscb07courseproject/files): android.system.ErrnoException: chmod failed: EACCES (Permission denied)
W/System.err: java.io.FileNotFoundException: /data/user/0/c.b.project/files/new_clients.txt (Permission denied)
W/System.err:     at java.io.FileOutputStream.open(Native Method)
W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
W/System.err:     at android.app.ContextImpl.openFileOutput(ContextImpl.java:506)
W/System.err:     at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:192)
W/System.err:     at EnterUserInfo.writeToFile(EnterUserInfo.java:69)

As you can see, it prints here meaning the permission is granted, but right after it gives a Permission Denied error. Any idea how to solve this?

Edit: On a side note, when it says that it tries to save to /data/user/0/cs.b07.cscb07courseproject/files, is that within the project or is that saved on my computer? Because when I go to my terminal and do cd /data/ or cd /data neither is found.

Edit: writeToFile() is called in the same class and file posted above, and this is the code (the function below is called when a user hits the "register" button in the UI:

public void createNewUser(View view) {
    // a data string is created here:
    // String data = "asd";
    writeToFile(data, this);
}

Edit 2: Please note that I did ask for permission at runtime in my verifyStoragePermissions() method. Unless something is wrong with that way of asking for permission (which I don't think it is because a prompt does appear which asks the user for permission), then I think the issue is with something else.

回答1:

You do not need any permissions to call openFileOutput(). This writes a file to the private application-specific data area, which is owned by your application.

Judging by these errors:

W/ContextImpl: Failed to ensure /data/user/0/c.b.project/files: mkdir failed: EACCES (Permission denied)
W/FileUtils: Failed to chmod(/data/user/0/cs.b07.cscb07courseproject/files): android.system.ErrnoException: chmod failed: EACCES (Permission denied)

It looks like someone has changed the file ownership (or access rights) on your application's private data directory /data/user/0/c.b.project/. This directory should be owned by your application's user ID and therefore your application should have the necessary rights to write to it.

Uninstall your app (which should delete that directory) and then reinstall your app (which should recreate the directory with the correct permissions).



回答2:

Requesting Permissions at Run Time

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app.

More about runtime permission
Refer Answer



回答3:

Hi firstly you have to check which android SDK version you are using

if it is less than 23 than you just have to put your permission in manifest file it work

if android version greater than 23 you should put all permission in manifest file as well as you should ask user permission for run time ( only first attempt )
for this you should follow this link https://stackoverflow.com/a/33162451/4741746

One more thing you can don is to change compileSdkVersion and buildToolsVersion to below 23 like 22 (but i will not suggest you for this because new features above 23 you can not be use )

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

   defaultConfig {
      minSdkVersion 16
      targetSdkVersion 23
   }
} 

if not working let me know