FileNotFoundException (permission denied) when trying to write file to sdcard in Android - java

As you can notice from title, I have a problem with writing file to sdcard in Android. I've checked this question but it didn't help me. I want to write file that will be in public space on sdcard so that any other app could read it.
First, I check if sdcard is mounted:
Environment.getExternalStorageState();
Then, I run this code:
File baseDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
baseDir.mkdirs();
File file = new File(baseDir, "file.txt");
try {
FileOutputStream out = new FileOutputStream(file);
out.flush();
out.close();
Log.d("NEWFILE", file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
I have:
<manifest>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application>
...
</application>
</manifest>
in my AndroidManifest.xml.
Exact error is this:
java.io.FileNotFoundException: /storage/1510-2908/Download/secondFile.txt: open failed: EACCES (Permission denied)
I'm testing my code on emulator (emulating Nexus5 API 23). My minimum required SDK version is 19 (4.4 Kitkat).
Also, everything works fine with writing files to private folder on sdcard with same code so I'd say former code should work too:
File newFile = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "esrxdtcfvzguhbjnk.txt");
newFile.getParentFile().mkdirs();
try {
FileOutputStream out = new FileOutputStream(newFile);
out.flush();
out.close();
Log.d("NEWFILE", newFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
Does anyone have any clue what could be the problem? Could it be that somehow KitKat 4.4 just doesn't allow writing to public space in sdcard anymore or?

Everything works fine with writing files to private folder on sdcard
Beginning with Android 4.4, these permissions are not required if you're
reading or writing only files that are private to your app. For more information, see saving files that are app-private.
FileNotFoundException (permission denied) when trying to write file to sdcard in Android
As you are trying to write the file in emulator having API 23(Marshmallow), You need to Request WRITE_EXTERNAL_STORAGE permission at runtime also. Check this and this for more detail.

Related

java.io.FileNotFoundException: /storage/emulated/0/Android/data/MyApplication/MyFile.ics. (No such file or directory) / Android Studio / Ical4j

I'm calling for your help, I'm stuck for my android project, and I can't find a solution.
Explanation :
I retrieve an .ics (iCalendar) file from a URL on the internet with the Apache Common library using FileUtils.copyURLToFile(url, file).
It works very well, my file is created with my data and it is readable.
I save my file in the path : /storage/emulated/0/Android/data/MyApplication/MyFile.ics.
I can see it in the files of the phone (Android Pie) and/or the emulator (Android Oreo) at this address. So it is well created and present.
But when I want to parse my file with the iCal4j library, I get an error with the line containing FileInputStream, telling me that my file or directory does not exist at this address.
EDIT
I specify that I check that my file exists with file.exist(). If it exists then it calls the function to parse my file. Where I have a problem with the FileInputStream.
So yes, file.exist() tells me that it exists.
File file = new File(Environment.getExternalStorageDirectory() + "/Android/data/MyApplication/MyFile.ics");
FileInputStream fin = new FileInputStream(file.getPath());
CalendarBuilder builder = new CalendarBuilder();
Calendar calendar = builder.build(fin);
I get one mistake.
My errors :
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Android/data/MyApplication/MyFile.ics (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:200)
at java.io.FileInputStream.<init>(FileInputStream.java:150)
at java.io.FileInputStream.<init>(FileInputStream.java:103)
My manifest.xml :
<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" />
and I also asked the user's permission to access the storage:
requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE}, 1);
I hope I was clear enough to get help, thank you.
try with following code File file = new File(Environment.getExternalStorageDirectory() + "/MyApplication/MyFile.ics");
If all the permissions are requested, it will still prompt that the permission request failed. It's probably the adaptation problem of Android 10.0. You can add it under
<application
...
android:requestLegacyExternalStorage="true"
...
>
https://developer.android.com/training/data-storage/use-cases
File file = new File(Environment.getExternalStorageDirectory()+"/Android/data/MyApplication/MyFile.ics");
if(file.createNewFile(){
FileInputStream fin = new FileInputStream(file.getPath());
// Your entire code
}
else{
//File exist already Handle it
}
TIP:
Replace (it is not mandatory just to reduce size of code)
Environment.getExternalStorageDirectory()+"/Android/data/MyApplication/MyFile.ics to getActivity().getExternalFilesDir(null)+"/MyFiles.ics"
No need Read and Write permission to Read & write in your persistent folder so remove it if possible.
AND if your app target above or equal to Android 10 then added
android:requestLegacyExternalStorage="true" inside application Tag
Like :
<application
....
android:requestLegacyExternalStorage="true"
....>

Access is denied for some particular file types using Java on Windows 7

I have tried the followings for .txt, .sql, .java with success BUT I can't write file with the extension with .pdf, .jpg, .zip.
File file = new File("d:/myFolder/something.txt");
File file = new File("d:/myFolder/something.sql");
File file = new File("d:/myFolder/something.java");
// Executed Successfully for the above 3 but java.io.FileNotFoundException (Access is denied) show for these files below.
File file = new File("d:/myFolder/something.jpg");
File file = new File("d:/myFolder/something.pdf");
File file = new File("d:/myFolder/something.zip");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(mpf.getBytes());
fos.close();
fos.flush();
} catch (Exception e) {
System.out.println(e.getMessage());
}
Project is being developed using spring MVC on Windows 7 (64 bit).
Perhaps there is an unusual antivirus or similar security product running on your Windows?
If so, either disable the antivirus or configure it to permit these filetypes.
So long as it is enabled, it is actually doing exactly what it is supposed to do by blocking these file-writes.

Can't read text file from the data folder or documents folder in the phone's internal storage

I am trying to read a hi.txt file present in the "Data" folder inside the phone's internal storage.
I tried the following:
try{
File dir = Environment.getDataDirectory();
File file = new File(dir, "hi.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
line = br.readLine());
}catch (Exception e) {
System.out.println(e.getMessage());
}
But, I get the exception: "/data/hi.txt" (no such file or directory)
I am sure the hi.txt file is there!
Same thing happens if I try opening it from the documents folder also in internal storage like this:
File dir= new File("/Documents/hi.txt");
What am I doing wrong? And how can I read a text file that is stored anywhere in the internal storage? like in the DCIM folder or the Documents folder or Movies or Pictures or Music ..etc ?
I need to use a public text file that can be accessed by any application on the phone.
As I can't add a comment, I have to use answer.
Have you tried with Environment.getDataDirectory().getAbsolutePath(), as you are right about the permissions in Manifest, you need them just for external storage. And the other part of the code looks well to me.

I can't write to /mnt/sdcard2 in Android

Now I'm making some version of File Manager in Andoid.
My permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
When I write new file to /mnt/sdcard (External Stroage) everything is allright.
But When i write new file to /mnt/sdcard2 (internal storage) I get IOException like
open failed: EACCES (Permission denied)
My full code:
try {
File existingFile = new File(path);
File newFile = new File(newPath);
if (!newFile.exists()) {
if (!isFolder)
{
newFile.createNewFile();
}
}
if (isFolder) {
FileUtils.copyDirectory(existingFile, newFile);
}
else
{
FileUtils.copyFile(existingFile, newFile);
}
} catch (IOException e) {
result = 1;
}
When i test my application I use real device.
My Path is like '/mnt/sdcard/Music/blabla' and so on
My Path is like '/mnt/sdcard/Music/blabla'
Do not use hardcoded paths as these may (and will) differ depending on device model or can even OS version. You got methods in Environment class to get you root folder of external storage and you should use it like getExternalStorageDirectory()
EDIT
. I need to get folder that contents folder like Music, DCIM, Download, but in Inner Storage of Smartphone
You cannot have "private" DCIM, Downloads really if you want to use system features like DownloadManager or external Camera app, because these apps will simply not be able to write to your private storage. So you either download/take photo yourself - then you can save the file whenever you want, or you use what is it now available, with all the pros and cons.
Name "external"/"internal" is a bit misleading nowadays, so do not take it too literally.

FileUtils.readFileToString IOException

I'm new to Android app development. Currently, I'm trying to get Android download folder path and log it. To do this, I use commons io library. I've got this code:
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.e("files", folder.listFiles().length + " items");
try {
String DFOLDER = FileUtils.readFileToString(folder);
Log.i(TAG2, DFOLDER);
}catch (IOException e){
Toast.makeText(getApplicationContext(), R.string.fail,
Toast.LENGTH_SHORT).show();
}
For some reason I'm getting IOException every time, but I'm receiving the amount of files in folder from 2nd line.
I've got this permissions in manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
FileUtils.readFileToString Reads the contents of a file into a String. Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) return a directory, not a file, so using readFileToString on it will throw an IOException. If you want to read the contents of all the files in the Download directory, do something like that.
File folder = Environment.getExternalStoragePublicDirectory(Environmeng t.DIRECTORY_DOWNLOADS);
for(File file:folder.listFiles()){
try {
String DFOLDER = FileUtils.readFileToString(file);
Log.i("File Contents ", DFOLDER);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
If there are too many files in that directory, it will probably throw an OutOfMemoryError.
EDIT: if you need the path of the foler use
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.i("Folder Path",folder.getAbsolutePath());
According to the Commons IO 2.4 API, the readFileToString method will take a file as parameter then read the contents of a file into a String. However,the getExternalStoragePublicDirectory method returns a folder instead of a file so calling readFileToString will throw an IO exception.

Categories

Resources