Alireza Farahani
Alireza Farahani

Reputation: 2529

permission denied on creating new file in external storage

I want to create a new file in external storage if that file doesn't exist already. I've already read similar questions in SO and have WRITE_EXTERNAL_STORAGE permission in my manifest. Testing on GenyMotion emulator with android 5.1 and xperia t with android 4.3 the result is same and I get "open failed: EACCES (Permission denied)" on file.createNewFile(). I checked in runtime and getExternalStorageState functoin return value is "MOUNTED".

Note: If I create the file manually, my code works perfectly and reads the content meaning that accessing to external storage is OK. I although write to external storage another place in my code using getExternalPublicStorage for saving captured image and it works fine!

File f = Environment.getExternalStorageDirectory();
File config = new File(f, "poinila config" + ".txt");
if (!config.exists()) {
    if (!config.createNewFile()) {
        // toast that creating directory failed
    } else {
        writeDefaultIpPort();
    }
}

Edit: path string is "/storage/sdcard0/poinila config.txt"

Upvotes: 5

Views: 6085

Answers (3)

neelabh
neelabh

Reputation: 477

well I think this is the new security feature introduced in android. Runtime permissions. You have to do something like this

           int hasReadExternalStoragePermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
            if(hasReadExternalStoragePermission != PackageManager.PERMISSION_GRANTED)
                if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE))
                    new AlertDialog.Builder(getContext())
                            .setMessage("You need to Allow access to Images to set a Company Logo")
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    requestPermission();
                                }
                            }).show();
                    else
                        requestPermission();
            else
                callChooser();

Upvotes: 2

ya man
ya man

Reputation: 547

I had the same issue. I think it is a missing / in the path. Try this:

config = new File(Environment.getExternalStorageDirectory() + "/" +  "poinila config.txt" );

Hope it helps

Upvotes: 0

Vaibhav Barad
Vaibhav Barad

Reputation: 625

Is your permission is right place in manifest file as

  <application>
        ...

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

Upvotes: 0

Related Questions