Permission denied when writing into sdCard - android

I'm trying write a file into SDCard, but I am getting error in logcat:
01-24 09:03:33.647: W/System.err(3353): java.io.FileNotFoundException: /mnt/sdcard/fun/itisfun.txt: open failed: EACCES (Permission denied)
01-24 08:24:28.007: W/System.err(3353): Caused by: libcore.io.ErrnoException: open failed: EACCES (Permission denied)
01-24 09:03:33.756: W/System.err(3353):at libcore.io.Posix.open(Native Method)
And here my code to write into SDCard:
File root = null;
try {
// check for SDcard
root = Environment.getExternalStorageDirectory();
Log.i(TAG,"path.." +root.getAbsolutePath());
//check sdcard permission
if (root.canWrite()){
File fileDir = new File(root.getAbsolutePath()+"/fun/");
fileDir.mkdirs();
File file = new File(fileDir, "itisfun.txt");
FileWriter filewriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(filewriter);
out.write("I m enjoying......dude");
out.close();
}
} catch(...) {
...
}
Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<permission android:name="android.permission.INTERNET"></permission>

For writing to the Sdcard you need to give the permission in your manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

You need to make sure you have the permission #Ram mentions, and the SD Card is mounted. You can check if it is mounted by:-
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
You should handle an unmounted card gracefully, but a common gotcha is if your phone is plugged in via the USB cable you may have it mounted via your desktop OS, which means it's not mounted by Android.
Thanks,
Ryan

Here's a bit of code I use,
public void yourMethod(){
File root = getDir(getApplicationContext());
try {
File fileDir = new File(root.getAbsolutePath()+"/fun/");
fileDir.mkdirs();
File file = new File(fileDir, "itisfun.txt");
FileWriter filewriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(filewriter);
out.write("I m enjoying......dude");
out.close();
} catch(...) {
...
}
}
public File getDir(Context context) {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
DIRECTORY_NAME);
else
cacheDir = context.getCacheDir();
return cacheDir;
}
If there is no external storage, it basically uses the phones internal cache (not good for large files)
Read this

If you're on 4.4, read here: http://www.androidcentral.com/kitkat-sdcard-changes Basically you can no longer read and write anywhere on the drive. You can only write to your private directory and directories you've become the owner of.

Check that your directory fun and the file itisfun.txt exists on the SDcard, if you want to make them by program, you have to add the permission:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
This permission allows the application to create file or directory, the permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> only allows the application to read and write the file that is already exist.
Make sure that your permission is outside of the <application> tag, usually before it.

Related

Unable to write to external storage

I'm trying to write data from the app's form into a .txt file but it won't work. I've put in an empty "record.txt" into the directory but nothing is written inside.
AndroidManifest.xml
...
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...
MainActivity.java
String statement = textView.getText.toString();
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
final File file = new File (root, "record.txt");
try {
FileWriter f = new FileWriter(file);
BufferedWriter buffwrite = new BufferedWriter(new FileWriter(file));
buffwrite.append(statement);
buffwrite.newLine();
buffwrite.flush();
buffwrite.close();
} catch (IOException e) {
e.printStackTrace();
}
Java doesn't automatically create a file when you just create reference you have to check if the files exist or not
if(file.exists()) { ... }. Else
file.createNewFile();
And make sure you have necessary permissions
You should ask for permission at runtime, WRITE_EXTERNAL_STORAGE is consider a dangerous permissions.
permissions overview
request permissions

Android mkdirs() doesn't work

I'm trying to generate a folder with my android application in my phone storage (not on the sdcard) but my mkdirs() is not working.
I have set the android.permission.WRITE_EXTERNAL_STORAGE in my manifest and use this basic code :
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "/MyDirName");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("App", "failed to create directory");
}
}
but it doesn't work ... The mkdirs is always at false and the folder is not created.
I have tried everything and looked at all the topics about it but nothing is working and I don't know why.
if you target and compile sdk is higher then lolipop then please refer this link
or
File sourcePath = Environment.getExternalStorageDirectory();
File path = new File(sourcePath + "/" + Constants.DIR_NAME + "/");
path.mkdir();
If you you the emulator and the Device File Explorer of Android Studio, be sure that you right-click over a folder of the emulator and then click on 'synchronize' to update the files displayed. The Device File Explorer doesn't update by itself in real time.
when writing code for android API 29 and above use the following permission in your application manifest (AndroidManifest.xml)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
Then in your java file add the following lines of code
`ActivityCompat.requestPermissions(this, new String[]
{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
PackageManager.PERMISSION_GRANTED);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
file = new File(Environment.getExternalStorageDirectory().getPath(), "MyDirName/");
if (!file.exists()) {
try {
file.mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
}
`

Open file from external storage in Android

This could probably be a fast fix but currently I am unable to get this working...
I have an asynctask where I am parsing a XML file. If I place an XML file in the assets folder i can open and parse it no problem.
But if I try to open a XML file from external storage it fails.
Here is my asynctask:
private class async extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
while (!isCancelled()) {
try {
NodeList nList;
Node node;
InputStream is = getAssets().open("file.xml");
// this works
File is = new File("/storage/emulated/0/test.xml");
// this fails
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
I am getting this error:
I/System.out: File path: /storage/emulated/0/test.xml
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/test.xml (Permission denied)
These permissions are in my manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Could someone tell me why I am getting this error?
Thanks!
I see your error message :
java.io.FileNotFoundException: /storage/emulated/0/test.xml
(Permission denied)
Remember that running on running Android 6.0 you must implement runtime permissions before you try to read or write the external storage.
setting this into your manifest.xml is not enough for devices with Android 6.0+:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You should not hardcode the path. You can try this:
String path = Environment.getExternalStorageDirectory() + File.separator + MY_DIR_NAME + File.separator + "file.xml"
You should not try to access the filesystem using absolute paths.
To retrieve the path of the SD card you can use:
Environment.getExternalStorageDirectory()
So if you want to create a file named test.xml
new File(Environment.getExternalStorageDirectory(),"test.xml");
this is the method I use to open a pdf file from the folder that I created in the internal storage (sd card) of my phone.
but first you need to asd the user for the permission , go to manifest and write down :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and in your main activity, you must implement runtime permissions before you try to read or write the external storage.
than use this method below don't forget to change the folder and file name
public void openPDF2(){
String path = Environment.getExternalStorageDirectory() + File.separator + "PDF folder 12"+ File.separator ;
File file = new File(path,fileName+".pdf");
String extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_NEW_TASK);
Uri uri = FileProvider.getUriForFile(GenerateQRActivity.this, GenerateQRActivity.this.getApplicationContext().getPackageName() + ".provider", file);
try {
intent.setDataAndType(uri, mimeType);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(intent, "choseFile"));
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG2, "openPDF2: the problem is : "+e.getMessage());
}
}

Creating Folder in Internal memory

I am unable to get the methods for creating folder in Internal Memory,
i gone through few conversations in Android create folders in Internal Memory and Problem facing in reading file from Internal memory of android. But still i am unable to meet my requirement.
My requirement is , I want to create a folder in Internal Memory, there i want to Store one video.
Thankyou you very much in advance for valuable feedbacks.
try the below
File mydir = context.getDir("users", Context.MODE_PRIVATE); //Creating an internal dir;
if (!mydir.exists())
{
mydir.mkdirs();
}
Here is the code which I am using for creating files in internal memory :
File myDir = context.getFilesDir();
// Documents Path
String documents = "documents/data";
File documentsFolder = new File(myDir, documents);
documentsFolder.mkdirs(); // this line creates data folder at documents directory
String publicC = "documents/public/api." + server;
File publicFolder = new File(myDir, publicC);
publicFolder.mkdirs(); // and this line creates public/api.myservername folder in internal memory
To create directory on phone primary storage memory (generally internal memory) you should use following code. Please note that ExternalStorage in Environment.getExternalStorageDirectory() does not necessarily refers to sdcard, it returns phone primary storage memory
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "MyDirName");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("App", "failed to create directory");
return null;
}
}
Directory created using this code will be visible to phone user. The other method (as in accepted answer) creates directory in location (/data/data/package.name/app_MyDirName), hence normal phone user will not be able to access it easily and so you should not use it to store video/photo etc.
You will need permissions, in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
File direct = new File(Environment.getExternalStorageDirectory()+"/folder_name");
if(!direct.exists()) {
if(direct.mkdir()); //directory is created;
}
There is a "cacheDirectory" in your "data/package_name" directory.
If you want to store something in that cache memory,
File cacheDir = new File(this.getCacheDir(), "temp");
if (!cacheDir.exists())
cacheDir.mkdir();
where this is context.
try {
File cashDir = new File(dir.getCanonicalPath(),"folder");
if(!(cashDir.exists())) cashDir.mkdirs();
} catch (IOException e) {
e.printStackTrace();
}

EACCESS Permission denied in Android

While writing file in External SD card I am getting an error EACCESS permission denied. I have set the permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
But the when I read the file I am successfully able to read it but not able to write the file. The code that I am using for writing the file in SD card is:
String path="mnt/extsd/Test";
try{
File myFile = new File(path, "Hello.txt"); //device.txt
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing SD "+myFile.getPath(),Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
System.out.println("Hello"+e.getMessage());
}
}
The path for the external storage card is mnt/extsd/. Thats why I am not able to use Environment.getExternalStorageDirectory().getAbsolutePath() which is giving me a path mnt/sdcard and this path is for internal storage path in my tablet. Please suggest why this is so n how can I resolve this
As I remember Android got a partial multi-storage support since Honeycomb, and the primary storage (the one you get from Environment.getExternalStorageDirectory, usually part of the internal eMMC card) is still protected by the permission WRITE_EXTERNAL_STORAGE, but the secondary storages (like the real removable SD card) are protected by a new permission android.permission.WRITE_MEDIA_STORAGE, and the protection level is signatureOrSystem, see also the discussion in this article.
If this is the case then it seems impossible for an normal app to write anything to the real sdcard without a platform signature...
From API level 19, Google has added API.
Context.getExternalFilesDirs()
Context.getExternalCacheDirs()
Context.getObbDirs()
Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions. Restricting writes in this way ensures the system can clean up files when applications are uninstalled.
Following is approach to get application specific directory on external SD card with absolute paths.
Context _context = this.getApplicationContext();
File fileList2[] = _context.getExternalFilesDirs(Environment.DIRECTORY_DOWNLOADS);
if(fileList2.length == 1) {
Log.d(TAG, "external device is not mounted.");
return;
} else {
Log.d(TAG, "external device is mounted.");
File extFile = fileList2[1];
String absPath = extFile.getAbsolutePath();
Log.d(TAG, "external device download : "+absPath);
appPath = absPath.split("Download")[0];
Log.d(TAG, "external device app path: "+appPath);
File file = new File(appPath, "DemoFile.png");
try {
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
Log.d(TAG, "file bytes : "+is.available());
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.d("ExternalStorage", "Error writing " + file, e);
}
}
Log output from above looks like:
context.getExternalFilesDirs() : /storage/extSdCard/Android/data/com.example.remote.services/files/Download
external device is mounted.
external device download : /storage/extSdCard/Android/data/com.example.remote.services/files/Download
external device app path: /storage/extSdCard/Android/data/com.example.remote.services/files/
I solved this problem by removing the android:maxSdkVersion="18" in uses-permission
in manifest file.
I.e. use this:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
instead of:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
Check if user is having external storage permission or not. If not then use cache dir for saving the file.
final boolean extStoragePermission = ContextCompat.checkSelfPermission(
context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED;
if (extStoragePermission &&
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) {
parentFile = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
}
else{
parentFile = new File(context.getCacheDir(), Environment.DIRECTORY_PICTURES);
}

Categories

Resources