Reputation: 701
Question is rather basic, but it is still driving me nuts: How can I create a simple text file to a publicly visible directory, say Downloads folder? The android I'm using uses android version 6.0.1 and the app itself has minimum sdk level 20.
I don't have a sdcard, but as far as I know, the terms Internal and External refer to the visibility and access rights to the directory: If only the app sees the file, it's internal. If the user sees the file, it's external.
First things first, I have the required uses-permission tags in the AnrdoidManifext.xml although I don't need the read permissions in the context of this question.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mylittleapp">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application>
<!-- Not relevant... right? -->
</application>
</manifest>
And then to the code itself. You can tell from debug logs that I'm getting a little frustrated with this.
public class LogFileWriter {
File mFile;
FileOutputStream mStream;
LogFileWriter(String filename) {
// Check if storage is available
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Log.d("LogFileWriter", "I'm not your state buddy!");
return;
}
File target = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if (!target.exists() && !target.mkdir()) {
Log.d("LogFileWriter", "I'm not your folder guy!");
return
}
mFile = new File(target, filename);
try {
if (!mFile.exists())
Log.d("LogFileWriter", "I'm not your file friend!");
else {
mStream = new FileOutputStream(mFile);
}
} catch (FileNotFoundException e) {
Log.d("LogFileWriter", "Exceptional!");
}
}
Here, the program fails at the !mFile.exist()
check and prints I'm not your file friend!
If I would add there the mFile.createNewFile()
, that would cause an IOException...
java.io.IOException: open failed: EACCES (Permission denied)
Eventhough the program should have the access to the public directory!
I have also tried to write the files to Context.getExternalFilesDir()
direcotry, but with the same results: I still dont' have the write access.
I also checked that where the Environment.getExternalStoragePublicDirectory
leads to. Its path is /storage/0/emulated/Download
.
How to get write permission to external storage? Any ideas?
Upvotes: 0
Views: 2092
Reputation: 701
As @SaravInfern and others pointed out, the problem was that in the newest versions of android I also have to request the write permissions during the runtime. Thank you guys!
https://developer.android.com/training/permissions/requesting.html
Upvotes: 1