2017-07-22 74 views
12

我試圖刪除位於路徑無法從外部存儲刪除文件編程

/storage/714D-160A/Xender/image/Screenshot_commando.png 

我到目前爲止已經做了一個文件:

try{ 
     String d_path = "/storage/714D-160A/Xender/image/Screenshot_commando.png"; 
     File file = new File(d_path); 
     file.delete(); 

    }catch(Exception e){ 

     e.printStackTrace(); 
    } 

和文件仍然是在它的位置(未刪除:()

清單文件我也已經獲准。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.STORAGE" /> 
+0

你是什麼錯誤gettng?添加你的logcat細節。 – huk

+0

如果您在Android M或更高版本的設備上進行測試,則需要運行時權限。 –

+0

我測試的設備與Android M – Secret

回答

5
public static boolean delete(final Context context, final File file) { 
    final String where = MediaStore.MediaColumns.DATA + "=?"; 
    final String[] selectionArgs = new String[] { 
      file.getAbsolutePath() 
    }; 
    final ContentResolver contentResolver = context.getContentResolver(); 
    final Uri filesUri = MediaStore.Files.getContentUri("external"); 

    contentResolver.delete(filesUri, where, selectionArgs); 

    if (file.exists()) { 

     contentResolver.delete(filesUri, where, selectionArgs); 
    } 
    return !file.exists(); 
} 
+0

此方法適用於在Android 5.0及更高版本上運行的Android設備嗎? – Rahulrr2602

+1

是的,它適用於Android 5.0及更高版本。 – Secret

+0

非常感謝。 – Rahulrr2602

3

使用Environment.getExternalStorageDirectory().getAbsolutePath()而不是硬編碼存儲路徑

String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath(); 
File f = new File(baseDir + "/714D-160A/Xender/image/Screenshot_commando.png"); 
boolean d = f.delete(); 
+0

感謝您的回答,但我想刪除外部存儲(存儲卡)file.and布爾返回false,文件是仍然在它的地方(不刪除).. – Secret

+0

@Secret你測試'Environment.getExternalStorageDirectory()。getAbsolutePath()'而不是'/ storage'嗎? – SiSa

+0

是的我測試但不適合我... @ SiSa – Secret

9

使用ContentResolver刪除媒體文件是錯誤的,併爲用戶提供了諸多問題。
只需在Jelly Bean(4.3)以上的Android版本上刪除ContentResolver中的信息,即可刪除sd-card上的文件。
它僅適用於KitKat(4.4)之前的Android版本。
這就是爲什麼Android團隊提供了DocumentProvider

爲什麼contentResolver.delete(...)錯了?
1.填補了sd-card
當您嘗試通過ContentResolver在Android版本比4.3更高的可刪除在sd-card的媒體文件,因爲contentResolver.delete(...)方法僅刪除信息的實際的媒體文件將保持不變(姓名,日期,路徑......),你最終會在你的sd-card上看到未註冊的媒體文件,而這些文件對於他們的存在已不知曉,這就是爲什麼你不能在你的畫廊看到他們,我們已經使用這種方法刪除了它們,但它們仍然存在,並且每次用戶嘗試刪除sd-card上的媒體文件時都會填寫sd-card

2.媒體文件(圖片,視頻,GIF格式......)會回來的畫廊
有許多應用程序在那裏特別是畫廊和文件管理器,那些會發現這些未註冊的媒體文件,將增加他們到ContentResolver再次作爲他們的正常行爲,而用戶假設他/她的不需要的媒體文件已經消失。 當然,沒有用戶想要他/她假設在演示過程中出現刪除的圖像或視頻。

那麼,刪除sd-card上的媒體文件的正確方法是什麼?
那麼,這已經回答了here使用DocumentProvider

+0

原來的問題甚至沒有提到ContentResolver。爲什麼你的答案關注於它?哦。我懂了。接受的答案使用contentresolver。 – Neo42