![](/img/trans.png)
[英]How to read files from external storage "Documents" in Android 10?
[英]Android: How to remove files from External storage?
我正在實現一個在外部存儲中生成和創建文件的應用程序。 我怎樣才能刪除它?
我添加了以下代碼,但仍然遇到同樣的問題。 請參閱下面的代碼:
String fullPath = "/mnt/sdcard/";
System.out.println(fullPath);
try{
File file = new File(fullPath, "audio.mp3");
if(file.exists()){
boolean result = file.delete();
System.out.println("Application able to delete the file and result is: " + result);
// file.delete();
}else{
System.out.println("Application doesn't able to delete the file");
}
}catch (Exception e){
Log.e("App", "Exception while deleting file " + e.getMessage());
}
在 LogCat 中,我讓應用程序能夠刪除文件,結果是:false 。 執行此操作后,我附上了我的屏幕截圖。
File file = new File(selectedFilePath);
boolean deleted = file.delete();
其中 selectedFilePath 是您要刪除的文件的路徑 - 例如:
/sdcard/YourCustomDirectory/ExampleFile.mp3
這是另一種方式,只需傳遞您的目錄名稱即可刪除其中的內容
例如"/sdcard/abc/yourdata"
public void deleteFiles(String path) {
File file = new File(path);
if (file.exists()) {
String deleteCmd = "rm -r " + path;
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(deleteCmd);
} catch (IOException e) {
}
}
}
我認為您忘記在 AndroidManifest.xml 文件中設置寫入權限,這就是 delete() 始終返回 false 的原因。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
嘗試以下代碼刪除自動創建的文件以及當您不知道它的存儲位置時:
public void clearApplicationData() {
File cache = getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(appDir, s));
Log.i("TAG",
"**************** File /data/data/APP_PACKAGE/" + s
+ " DELETED *******************");
}
}
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
它非常簡單:
File file = new File(YOUR_IMAGE_PATH).delete();
if(file.exists())
file.delete();
希望它會幫助你。
File file = new File(selectedFilePath);
boolean deleted = file.delete();
路徑將類似於: /mnt/Pictures/SampleImage.png
public void deleteOnExit ()
安排此文件在 VM 正常終止時自動刪除。
請注意,在Android上,應用程序生命周期不包括VM終止,因此調用此方法並不能確保文件被刪除。 相反,您應該使用最合適的:
使用 finally 子句手動調用 delete()。 維護您自己的一組要刪除的文件,並在應用程序生命周期中的適當時間點對其進行處理。 使用 Unix 技巧,在所有讀者和作者打開文件后立即刪除該文件。 沒有新的讀者/作者將能夠訪問該文件,但所有現有的讀者/作者仍然可以訪問,直到最后一個關閉文件。
試試這個它會從外部存儲中刪除文件。
public void deleteFromExternalStorage(String fileName) {
String fullPath = "/mnt/sdcard/";
try
{
File file = new File(fullPath, fileName);
if(file.exists())
file.delete();
}
catch (Exception e)
{
Log.e("App", "Exception while deleting file " + e.getMessage());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.