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.
Related
I have a question.
How can I save a file from network to the external storage of the android device, with
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)
being depricated?
My Code:
private void download(Context mContext) throws IOException {
String requestUrl = "http://someresource/..."
URL url = new URL(requestUrl);
InputStream in = url.openStream();
mContext.getFilesDir();
URI uri = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MUSIC).toURI();
Files.copy(in, Paths.get(uri.getPath() + "/_test.mp3"), StandardCopyOption.REPLACE_EXISTING);
in.close();
System.out.println("finished!");
}
I get the error W/System.err: java.nio.file.AccessDeniedException: /storage/emulated/0/Music/_test.mp3
I also read the article https://developer.android.com/training/data-storage/shared/media#java
but I suppose this is meant to be more of a guideline to tamper with existing media files, like searching or editing file tags etc. and not simply saving a file in the media directory.
Update:
My app needs to fulfill two tasks. I want to save an mp3 file to the above mentioned directory and also read files from this directory.
Below Q: Working with Environment.getExternalStorageDirectory().getPath()+"/Music"; returns the Music-Folder on the built-in flash memory of the Android device.
In that manner I want to know how to get the Music-Folder on the SD-Card of the Android device (when its plugged in).
Since Q: the above Method returns a directory, which is no longer directly accessible to apps. The tasks I want to fulfil are the same as the ones mentioned above.
As #blackapps supposed, using the MediaStore Class is in Q preferable. But how exactly do I do that?
For android 10 and 11 add this line to your <application> element in the android manifest file.
hope it will work:
<application
android:requestLegacyExternalStorage="true"
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"
....>
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.
I am trying to output numeric values one at a time from an Android application I'm writing, but I'm having a lot of trouble figuring out what's going on. Tried looking for answers, but only confused further. This strikes me as something that should be relatively straightforward, so I feel pretty dumb for being so confused by it.
String directory = Environment.getExternalStorageDirectory().getAbsolutePath();
When I log the directory I get a path "/storage/emulated/0" Where is that? Is that different from what I would get if I wasn't debugging?
Then I have:
String fileName = directory + "/Android/data/com.sample.app/files/test.txt"
File myFile = new File(fileName);
FileOutputStream fos;
try {
fos = new FileOutputStream(myFile);
String text = "Test text\n";
fos.write(text.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
I tried using the Windows Explorer to figure out where stuff is saving and/or is supposed to be saved but I don't see it. This is code based on the information in this link: http://developer.android.com/guide/topics/data/data-storage.html, but I really don't understand where the "/storage/emulated/0" comes from and how I either access that location or get rid of it.
EDIT: Right now I just want to save all the numbers so I can check what is coming out. The numbers are recorded from the audio input.
EDIT: Using the ASTRO File app on my phone revealed the files
Didn't need the "/Android/data/com.sample.app/files/" part, don't know how to use that.
Path wrong?
/storage/emulated/0 is a path at your filesystem which represents the external storage. At earlier versions of Android we often had /mnt/sdcard/ or something similiar, but many devices today don't have a sdcard but emulate an external storage anyway.
To view the files at your Android filesystem I'd recommend to use an App like Astro File Manager. Just take a look if your file has been written.
One possible mistake could be, that you you are missing a File.separator between your directory and the local path.
String fileName = directory + File.seperator + "Android/data/com.sample.app/file/test.txt"
Directory created?
You should also make sure, that the directory exists by calling myDir.mkDirs();, where myDir is the complete path without the filename.
To create the directory you can use the following code
directory = directory + "/Android/data/com.sample.app/file/test.txt"
new File(directory).mkDirs();
Uses-Permission in Manifest?
Last error source could be, that you might miss the external storage permission, you need a
You also need to make sure, that you require the permission for writing to the external storage. Take a look for <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in your Android Manifest file.
I see a bunch of other people asking this same question, but none of the solutions posted helped me.
I'm trying to write a (binary) file to external storage from my Android app.
I put <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> into my manifest, but I still can't manage to create any files. The code I'm using to create files is
File folder = new File(Environment.getExternalStorageDirectory(), SAVE_DIRECTORY);
File toWrite = new File(folder, "save.bin");
if(!toWrite.exists()){
try {
if(!folder.mkdirs())
Log.e("Save", "Failed to create directories for save file!");
toWrite.createNewFile();
} catch (IOException e) {
Log.e("Save", "Failed to create save file! " + e.getMessage());
}
}
The call to mkdirs() fails, and the createNewFile() throws the IOException (ENOENT, because the directory doesn't exist)
Anybody know what's up? I've even tried rebooting my device. I'm on API level 8 on a Nexus 7, if it makes any difference.
first you should check the ExternalStorageState
public static boolean isSDCARDAvailable(){
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
if this method isSDCARDAvailable return true, then use your code
add the permissions:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
The documentation says that starting in API level 19, WRITE_EXTERNAL_STORAGE is not required to read/write files in your application-specific directories returned by getExternalFilesDir(String) and getExternalCacheDir(). However if you don't want to write files there and instead want to write files to getExternalStorageDirectory(), under API 23 or higher you have to request permission at run time using requestPermissions(). Once I did that I was able to create a directory in getExternalStorageDirectory().
I was suffering this issue as well and everything was properly configured in my app, i.e., I had the read and write permissions for external storage.
My problem was in the way I was creating the path to store my files:
private val LOG_BASE_PATH = Environment.getExternalStorageDirectory().path + "myFolder"
Note that it is necessary to include the "/" as follows:
private val LOG_BASE_PATH = Environment.getExternalStorageDirectory().path + "/myFolder/"
Without this, you won't be able to create the folder. Android won't fail, so you might think that there are issues with your phone configuration or app permissions.
Ideally, this helps somebody to save some precious time.