简体   繁体   中英

How to delete file or directory from root directory of external storage (...removable sdcard root directory)

i'm building a storage manager app but i can't delete/rename/create files on external storage

i used file.delete() code for internal storage and it's works greate, but it's not working on external storage files, also tried

DocumentFile fileUri = DocumentFile.fromFile(file);
fileUri.delete();

and it's dosent work either

how can i write to external storage without using the Intent.ACTION_OPEN_DOCUMENT_TREE each time the user wants to delete/rename/create file?

  • the files path are /storage/5A85-D438/*files or a folders*

  • already added the folowing permissions:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

including android:requestLegacyExternalStorage="true"

You can just use DocumentFile with createFile on an Output Stream.

if (!t.getString("muri", "").equals("")) {

try{
muri = t.getString("muri", "");
Uri treeUri = Uri.parse(muri);

final int takeFlags =
intent.getFlags() & 
(Intent.FLAG_GRANT_READ_URI_PERMISSION | 
Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
this.getContentResolver()
.takePersistableUriPermission(treeUri, takeFlags);

DocumentFile mr = DocumentFile.fromTreeUri(this, treeUri);
DocumentFile nf = mr.createFile("text/plain", "JAMZ");

OutputStream os = 
getContentResolver().openOutputStream(nf.getUri());
os.write(pass.getBytes());
os.close(); 

wuri = nf.getUri().toString();
t.edit().putString("wuri", wuri).commit();

} catch (Exception e) {}}

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