2009-08-08 133 views
126

我正在创建一个文件作为附件发送到电子邮件。现在我想在发送电子邮件后删除图像。有没有办法删除文件?我试过myFile.delete();但它没有删除文件。如何从SD卡中删除文件?


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

+0

您需要提供有关该问题的更多信息,例如您正在使用哪种语言,您如何访问SD卡等。 – Amok 2009-08-08 09:38:12

+0

您是否正在刷新对磁盘的更改? – 2009-08-08 09:47:47

+10

@Amuck我认为假设他使用Java是安全的,因为他没有指定。 – 2009-08-10 04:41:17

回答

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

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

/sdcard/YourCustomDirectory/ExampleFile.mp3

+0

我认为内心的孩子不会被删除..你必须删除所有的内心孩子。看到我的答案如下。 – Nepster 2014-05-15 07:56:45

+1

不幸的是,这不适用于Android 4.4+。请参阅下面的答案。 – 2014-05-20 13:44:02

+0

我不明白这是如何工作的许多人。 “删除”在Android Studio中看起来很灰。 – TheOnlyAnil 2015-06-06 11:18:48

79

你也有,如果赋予权限您正在使用> 1.6 SDK

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

in AndroidManifest.xml文件

16

Android的上下文有以下方法:

public abstract boolean deleteFile (String name) 

我相信这会做你想要用正确的应用premissions什么上面列出。

+2

这应该是正确的答案。 '上下文。DELETEFILE(文件名);' – Lisandro 2015-08-22 22:49:01

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()); 
} 

本准则将帮助你。而在Android清单你必须获得许可,进行修改..

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

文件[]可以为空,如果: 'file.exists:真 file.isDirectory:真 file.canRead:假 file.canWrite:FALSE' – Andreyua 2017-06-04 14:13:51

11

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

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

     fileOrDirectory.delete(); 
    } 
33

适用于Android的4.4+更改

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

作为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; 
    } 
} 
+1

不工作的注3。我得到错误“MediaProvider:无法删除/mnt/extSdCard/test.zip” – iscariot 2014-07-02 10:20:59

+2

我在4.4.4上有一个无根据的Moto X,并没有问题写入/ sdcard/mydirectory – Rob 2014-07-29 14:54:15

+0

“不幸的是,它不再工作更新的Kitkat版本,它已全部被锁定。“引自作者“ghisler(作者)” – HendraWD 2016-04-04 09:46:40

7

这对我的作品:(从库中删除图像)

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

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

context.sendBroadcast()是做什么的? – Megaetron 2015-12-01 09:47:08

+0

基本上,它将意向(要执行的操作)发送/广播给与此意图匹配的所有接收者。 [链接](http://developer.android.com/reference/android/content/Context.html) – Jiyeh 2015-12-01 10:01:03

0

这为我工作。

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

String my_Path = Environment.getExternalStorageDirectory()+myFile; 

File f = new File(my_Path); 
Boolean deleted = f.delete(); 
1

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

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

String myPath = Environment.getExternalStorageDirectory()+myFile; 

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

我认为这是明显的... 首先你必须知道你的文件的位置。 秒,,, Environment.getExternalStorageDirectory()是谁得到你的应用程序目录的方法。 最后,处理文件的类文件...

1

我在4.4上运行的应用程序有类似的问题。我所做的只是一种破解。

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

即。

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

试试这个。

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

从Apache的百科全书

0
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 
        } 
+0

你需要提供一些关于你的代码的解释! :) – 2017-05-13 17:46:09

+0

读取文件getExternalStorageDirectory +添加“/音乐/”它是我的路径 - > mypath =/storage/sdcard/Music /。检查文件是否存在并读取。删除如果存在。这是删除目录中的所有列表音乐音乐 – 2017-05-15 17:14:48

+0

将相同的答案添加到答案! :) – 2017-05-15 17:23:39

0
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(); 
0

您可以删除文件如下:

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()); 
    } 
}