Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.io.IOException: Permission denied cannot create file

Tags:

android

I follow this tutorial to take photo and save into device storage, but when I execute it, it got an exception

java.io.IOException: Permission denied 
 on line:

File image = File.createTempFile(imageFileName, ".jpg", storageDir);

How to solve this?

private File createImageFile() throws IOException
{
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "Camera");
    File image = File.createTempFile(imageFileName, ".jpg", storageDir);

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}

--Edit--
Here is my manifests

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.idea.takephoto">

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>

like image 736
Newbie Avatar asked Dec 09 '16 04:12

Newbie


2 Answers

As in the Android Documentation, you need to write to the external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:

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

If you use API 23 (Marshmallow) and above, you need to Requesting Permissions at Run Time because it's a Dangerous Permission.

like image 138
ישו אוהב אותך Avatar answered Sep 29 '22 05:09

ישו אוהב אותך


If your target api level is >=29 or you are using android 10 then please add following line in your app's manifest file in application tag

android:requestLegacyExternalStorage="true"

like image 43
androiduser Avatar answered Sep 29 '22 03:09

androiduser