I am very new into the android development. In this project, I am trying to create a JSON objects and then want to write that JSON object into a file in SD card but I am getting the following exception: W/System.err: java.io.FileNotFoundException: /storage/emulated/0/avinash1.json: open failed: EACCES (Permission denied) Though I have even added the user-permission in the manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.raviteja.youexample">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_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>
</application>
package com.example.raviteja.youexample;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONObject obj = new JSONObject();
try {
obj.put("age", new Integer(100));
obj.put("name", "Ravi");
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray list1 = new JSONArray();
JSONObject pnObj = new JSONObject();
try {
pnObj.put("num", "99009900");
pnObj.put("type", "mhgchmc");
list1.put(pnObj);
obj.put("phoneNumber", list1);
} catch (JSONException e) {
e.printStackTrace();
}
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath());
dir.mkdirs();
File file = new File(dir, "avinash1.json");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println(obj.toString());
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}