【问题标题】:How to delete a file from SD card?如何从 SD 卡中删除文件?
【发布时间】:2009-08-08 07:54:14
【问题描述】:

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

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


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

【问题讨论】:

  • 您需要提供有关该问题的更多信息,例如您使用的语言、您访问 SD 卡的方式等。
  • 您是否将更改刷新到磁盘?
  • @Amuck 我认为可以安全地假设他正在使用 Java,因为他没有指定。

标签: android android-sdcard


【解决方案1】:
File file = new File(selectedFilePath);
boolean deleted = file.delete();

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

/sdcard/YourCustomDirectory/ExampleFile.mp3

【讨论】:

  • 我认为内部孩子没有被删除..你必须删除所有内部孩子。请参阅下面的答案..
  • 不幸的是,这不适用于 Android 4.4+。请参阅下面的答案。
  • 我不明白这对许多人来说是如何工作的。 “已删除”在 Android Studio 中显示为灰色。
  • 是的,我发送的路径像“file:///storage/...”这样不起作用
  • @stevo.mit 你找到解决方案了吗?我也面临同样的问题,无法从 Android 4.4+ 以上的 sdcard 中删除文件。但同样的代码适用于 4.3/
【解决方案2】:

如果您使用>1.6 SDK,您还必须授予权限

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

AndroidManifest.xml 文件中

【讨论】:

  • 但对于可移动 SD卡存储,您还需要ContentResolver
【解决方案3】:

Android 4.4+ 的变化

应用不允许写入 (删除、修改...)外部存储except 到他们的包特定目录。

如 Android 文档所述:

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

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

有一个great article explaining (4.4+) external storage permissions change

您可以阅读more about workaround here。 解决方法源代码来自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; 
   } 
}

【讨论】:

  • 不适用于 note3。我收到错误“MediaProvider:无法删除 /mnt/extSdCard/test.zip”
  • 我在 4.4.4 上有一个无根的 Moto X,写入 /sdcard/mydirectory 没有问题
  • “不幸的是,它不再适用于新版本的 Kitkat,它已全部被锁定。”引自作者“ghisler(Author)”
  • Android 越来越封闭自己。我们最终会得到一个丑陋的 iOS 副本!
  • 这对我来说失败了(Android 7.1)。它总是返回false 并且不会删除文件:-(
【解决方案4】:

Android Context 有如下方法:

public abstract boolean deleteFile (String name)

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

【讨论】:

  • 这应该是正确的答案。 context.deleteFile(filename);
【解决方案5】:

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

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

    fileOrDirectory.delete();
}

【讨论】:

    【解决方案6】:

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

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

    【讨论】:

    • context.sendBroadcast() 有什么作用?
    • 基本上,它将意图(要执行的操作)发送/广播到与此意图匹配的所有接收者。 link
    【解决方案7】:
     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());
     }
    

    此代码将帮助您..并且在 Android Manifest 中您必须获得许可才能进行修改..

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

    【讨论】:

    • files[] 可以为空,如果:file.exists:true file.isDirectory:true file.canRead:false file.canWrite:false
    • 我猜你们完全不知道有些安卓手机限制了对 sd 卡的写入权限。
    【解决方案8】:

    试试这个。

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

    来自 Apache Commons

    【讨论】:

      【解决方案9】:

      对不起:由于站点验证,我之前的代码中有错误。

      String myFile = "/Name Folder/File.jpg";  
      
      String myPath = Environment.getExternalStorageDirectory()+myFile;  
      
      File f = new File(myPath);
      Boolean deleted = f.delete();
      

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

      【讨论】:

        【解决方案10】:

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

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

        即。

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

        【讨论】:

          【解决方案11】:

          这对我有用。

          String myFile = "/Name Folder/File.jpg";  
          
          String my_Path = Environment.getExternalStorageDirectory()+myFile;  
          
          File f = new File(my_Path);
          Boolean deleted = f.delete();
          

          【讨论】:

            【解决方案12】:
            private boolean deleteFromExternalStorage(File file) {
                                    String fileName = "/Music/";
                                    String myPath= Environment.getExternalStorageDirectory().getAbsolutePath() + fileName;
            
                                    file = new File(myPath);
                                    System.out.println("fullPath - " + myPath);
                                        if (file.exists() && file.canRead()) {
                                            System.out.println(" Test - ");
                                            file.delete();
                                            return false; // File exists
                                        }
                                        System.out.println(" Test2 - ");
                                        return true; // File not exists
                                }
            

            【讨论】:

            • 您需要对您的代码提供一些解释! :)
            • 读取文件 getExternalStorageDirectory + 添加 "/Music/" 这是我的路径 -> mypath = /storage/sdcard/Music/。检查文件存在或不存在并读取它。如果存在则删除。这是删除目录 Music 中的所有列表音乐
            • 在答案中添加相同的内容! :)
            【解决方案13】:

            您可以按如下方式删除文件:

            File file = new File("your sdcard path is here which you want to delete");
            file.delete();
            if (file.exists()){
              file.getCanonicalFile().delete();
              if (file.exists()){
                deleteFile(file.getName());
              }
            }
            

            【讨论】:

              【解决方案14】:
              File filedel = new File("/storage/sdcard0/Baahubali.mp3");
              boolean deleted1 = filedel.delete();
              

              或者,试试这个:

              String del="/storage/sdcard0/Baahubali.mp3";
              File filedel2 = new File(del);
              boolean deleted1 = filedel2.delete();
              

              【讨论】:

              • 你的两个例子都差不多。此外,投票得最高的答案正好告诉我们这样做。看不到这个答案增加了什么问题。此外,这不适用于从 Android Kitkat IIRC 开始的外部存储(如 SD 卡)中的文件
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-08-07
              • 1970-01-01
              • 2018-07-09
              • 1970-01-01
              相关资源
              最近更新 更多