Android 如何从SD卡中删除文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1248292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:50:53  来源:igfitidea点击:

How to delete a file from SD card?

androidandroid-sdcard

提问by mudit

I am creating a file to send as an attachment to an email. Now I want to delete the image after sending the email. Is there a way to delete the file?

我正在创建一个文件作为电子邮件的附件发送。现在我想在发送电子邮件后删除图像。有没有办法删除文件?

I have tried myFile.delete();but it didn't delete the file.

我试过了,myFile.delete();但它没有删除文件。



I'm using this code for Android, so the programming language is Java using the usual Android ways to access the SD card. I am deleting the file in the onActivityResultmethod, when an Intentis returned to the screen after sending an email.

我将此代码用于 Android,因此编程语言是 Java,使用通常的 Android 方式访问 SD 卡。onActivityResultIntent发送电子邮件后返回屏幕时,我正在删除方法中的文件。

回答by Niko Gamulin

File file = new File(selectedFilePath);
boolean deleted = file.delete();

where selectedFilePath is the path of the file you want to delete - for example:

其中 selectedFilePath 是您要删除的文件的路径 - 例如:

/sdcard/YourCustomDirectory/ExampleFile.mp3

/sdcard/YourCustomDirectory/ExampleFile.mp3

回答by neeloor2004

Also you have to give permission if you are using >1.6 SDK

如果您使用的是 >1.6 SDK,您也必须给予许可

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

in AndroidManifest.xmlfile

AndroidManifest.xml文件中

回答by stevo.mit

Change for Android 4.4+

更改为 Android 4.4+

Apps are not allowedto write(delete, modify ...)to externalstorage exceptto their package-specificdirectories.

应用程序都不允许(删除,修改...)外部存储除了特有的包目录。

As Android documentation states:

正如 Android 文档所述:

"Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions."

“不得允许应用程序写入辅助外部存储设备,除非在合成权限允许的特定于包的目录中。”

However nasty workaroundexists (see code below). Tested on Samsung Galaxy S4, but this fix does't work on all devices. Also I wouldn't count onthis workaround being available in futureversions of Android.

但是存在令人讨厌的解决方法(请参阅下面的代码)。在三星 Galaxy S4 上进行了测试,但此修复程序不适用于所有设备。此外,我不会指望未来版本的 Android 中提供这种解决方法。

There is a great article explaining (4.4+) external storage permissions change.

有一篇很棒的文章解释了 (4.4+) external storage permissions change

You can read more about workaround here. Workaround source code is from this site.

您可以在此处阅读有关解决方法的更多信息。解决方法源代码来自此站点

public class MediaFileFunctions 
{
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static boolean deleteViaContentProvider(Context context, String fullname) 
    { 
      Uri uri=getFileUri(context,fullname); 

      if (uri==null) 
      {
         return false;
      }

      try 
      { 
         ContentResolver resolver=context.getContentResolver(); 

         // change type to image, otherwise nothing will be deleted 
         ContentValues contentValues = new ContentValues(); 
         int media_type = 1; 
         contentValues.put("media_type", media_type); 
         resolver.update(uri, contentValues, null, null); 

         return resolver.delete(uri, null, null) > 0; 
      } 
      catch (Throwable e) 
      { 
         return false; 
      } 
   }

   @TargetApi(Build.VERSION_CODES.HONEYCOMB)
   private static Uri getFileUri(Context context, String fullname) 
   {
      // Note: check outside this class whether the OS version is >= 11 
      Uri uri = null; 
      Cursor cursor = null; 
      ContentResolver contentResolver = null;

      try
      { 
         contentResolver=context.getContentResolver(); 
         if (contentResolver == null)
            return null;

         uri=MediaStore.Files.getContentUri("external"); 
         String[] projection = new String[2]; 
         projection[0] = "_id"; 
         projection[1] = "_data"; 
         String selection = "_data = ? ";    // this avoids SQL injection 
         String[] selectionParams = new String[1]; 
         selectionParams[0] = fullname; 
         String sortOrder = "_id"; 
         cursor=contentResolver.query(uri, projection, selection, selectionParams, sortOrder); 

         if (cursor!=null) 
         { 
            try 
            { 
               if (cursor.getCount() > 0) // file present! 
               {   
                  cursor.moveToFirst(); 
                  int dataColumn=cursor.getColumnIndex("_data"); 
                  String s = cursor.getString(dataColumn); 
                  if (!s.equals(fullname)) 
                     return null; 
                  int idColumn = cursor.getColumnIndex("_id"); 
                  long id = cursor.getLong(idColumn); 
                  uri= MediaStore.Files.getContentUri("external",id); 
               } 
               else // file isn't in the media database! 
               {   
                  ContentValues contentValues=new ContentValues(); 
                  contentValues.put("_data",fullname); 
                  uri = MediaStore.Files.getContentUri("external"); 
                  uri = contentResolver.insert(uri,contentValues); 
               } 
            } 
            catch (Throwable e) 
            { 
               uri = null; 
            }
            finally
            {
                cursor.close();
            }
         } 
      } 
      catch (Throwable e) 
      { 
         uri=null; 
      } 
      return uri; 
   } 
}

回答by Yossi

Android Context has the following method:

Android Context 有以下方法:

public abstract boolean deleteFile (String name)

I believe this will do what you want with the right App premissions as listed above.

我相信这将使用上面列出的正确应用程序权限来满足您的需求。

回答by Jawad Zeb

Recursively delete all children of the file ...

递归删除文件的所有子文件...

public static void DeleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory()) {
        for (File child : fileOrDirectory.listFiles()) {
            DeleteRecursive(child);
        }
    }

    fileOrDirectory.delete();
}

回答by Jiyeh

This works for me: (Delete image from Gallery)

这对我有用:(从图库中删除图片)

File file = new File(photoPath);
file.delete();

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(photoPath))));

回答by Vivek Elangovan

 public static boolean deleteDirectory(File path) {
    // TODO Auto-generated method stub
    if( path.exists() ) {
        File[] files = path.listFiles();
        for(int i=0; i<files.length; i++) {
            if(files[i].isDirectory()) {
                deleteDirectory(files[i]);
            }
            else {
                files[i].delete();
            }
        }
    }
    return(path.delete());
 }

This Code will Help you.. And In Android Manifest You have to get Permission to make modification..

此代码将帮助您.. 在 Android Manifest 中,您必须获得权限才能进行修改..

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

回答by Rahul Giradkar

Try this.

尝试这个。

File file = new File(FilePath);
FileUtils.deleteDirectory(file);

from Apache Commons

来自 Apache Commons

回答by Denis IJCU

Sorry: There is a mistake in my code before because of the site validation.

抱歉:之前我的代码有错误,因为网站验证。

String myFile = "/Name Folder/File.jpg";  

String myPath = Environment.getExternalStorageDirectory()+myFile;  

File f = new File(myPath);
Boolean deleted = f.delete();

I think is clear... First you must to know your file location. Second,,, Environment.getExternalStorageDirectory()is a method who gets your app directory. Lastly the class File who handle your file...

我想很清楚......首先你必须知道你的文件位置。其次,,,Environment.getExternalStorageDirectory()是一种获取您的应用程序目录的方法。最后是处理您的文件的类 File...

回答by kkm

I had a similar issue with an application running on 4.4. What I did was sort of a hack.

我在 4.4 上运行的应用程序遇到了类似的问题。我所做的有点像黑客。

I renamed the files and ignored them in my application.

我重命名了这些文件并在我的应用程序中忽略了它们。

ie.

IE。

File sdcard = Environment.getExternalStorageDirectory();
                File from = new File(sdcard,"/ecatAgent/"+fileV);
                File to = new File(sdcard,"/ecatAgent/"+"Delete");
                from.renameTo(to);