简体   繁体   中英

Write to SD card Android

I want to give the users of my application the choice to save to the internal phone memory or to an SD card. If I create a File from the user's choice, the URI (without the file name) is something like:

Internal: content:/com.android.externalstorage.documents/tree/primary%3A

SD: content:/com.android.externalstorage.documents/tree/760E-F734%3A

However, if I try to write a file to these directories using the following code I get the error java.io.IOException: No such file or directory :

File writePath = new File("content:/com.android.externalstorage.documents/tree/primary%3A")

File file = new File(writePath, fileName);

try {
    file.createNewFile();
} catch (IOException e) {
    Log.e("saveSurvey", "Failed to create file!" + e.getMessage());
    return false;
}

So the file would be written somewhere like this:

content:/com.android.externalstorage.documents/tree/primary%3A/[my file name]

I have declared the WRITE_EXTERNAL_STORAGE permission in the manifest, so I guess it is not a permissions issue but more of an invalid path issue.

If these are not valid file paths, how would I go about writing to the SD card? Using Environment.getExternalStorageDirectory() always writes to the internal storage of my device ('/storage/emulated/0').

Please check your File Path. Call a getAbsolutePath() function And checked writePath

File writePath = new File("content:/com.android.externalstorage.documents/tree/primary%3A")
if(writePath.exists() && writePath.isDirectory()) {
    //File extensions can be declared 
       File file = new File(writePath.getAbsolutePath(), fileName+ extensions);
}

You getting this error because the path is different in different devices.

Try to use Environment.getExternalStorageDirectory() as writePath

Keep in mind in android 6 and above you must request permission at runtime

File works only with filesystem paths, or with file:// URIs, and you have a content:// URI here. (In addition, to create a file from a URI you would pass that as a Uri , not as a string.)

Depending on what you are trying to do with the file, DocumentFile may work for you. It is designed to provide an interface similar to File but built around the Storage Access Framework. You can obtain input and output streams for the file created that way and do some basic file operations.

The one thing that is a pain is anything involving standard Java libraries which expect a File argument, as there is no official way to get from a content:// URI to an actual File instance—apart from hacks which may cease to work after the next update, or on the one device that has not been considered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM