如何从SD卡中删除文件?

mud*_*dit 129 android android-sdcard

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

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


我正在使用Android的这个代码,因此编程语言是使用通常的Android方式访问SD卡的Java.当我在发送电子邮件后返回到屏幕onActivityResult时,我正在删除该方法中的文件Intent.

Nik*_*lin 357

File file = new File(selectedFilePath);
boolean deleted = file.delete();
Run Code Online (Sandbox Code Playgroud)

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

/sdcard/YourCustomDirectory/ExampleFile.mp3

  • 不幸的是,这不适用于Android 4.4+.请参阅下面的答案. (2认同)

小智 78

如果您使用的是> 1.6 SDK,则必须同意

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Run Code Online (Sandbox Code Playgroud)

AndroidManifest.xml文件中


ste*_*mit 34

Android 4.4及更改

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

正如Android文档所述:

"不得允许应用程序写入辅助外部存储设备,但合成权限允许的特定于程序包的目录除外."

但是存在令人讨厌的解决方法(参见下面的代码).在三星Galaxy S4上测试过,但此修复程序无法在所有设备上运行.此外,我不会指望将来的Android版本中提供此解决方法.

有一篇很棒的文章解释了(4.4+)外部存储权限的变化.

您可以在此处详细了解解决方法.解决方法源代码来自此站点.

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; 
   } 
}
Run Code Online (Sandbox Code Playgroud)

  • 我在4.4.4上有一个无根的Moto X,写入/ sdcard/mydirectory没问题 (2认同)

Yos*_*ssi 17

Android Context有以下方法:

public abstract boolean deleteFile (String name)
Run Code Online (Sandbox Code Playgroud)

我相信这将通过上面列出的正确的应用程序预备做你想做的事情.

  • 这应该是正确的答案.`context.deleteFile(文件名);` (3认同)

Xar*_*mer 11

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

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

        fileOrDirectory.delete();
    }
Run Code Online (Sandbox Code Playgroud)


Jiy*_*yeh 9

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

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

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(photoPath))));
Run Code Online (Sandbox Code Playgroud)

  • context.sendBroadcast()做什么? (2认同)

小智 6

 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());
 }
Run Code Online (Sandbox Code Playgroud)

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

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Run Code Online (Sandbox Code Playgroud)