131

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.


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 onActivityResult method, when an Intent is returned to the screen after sending an email.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
mudit
  • 25,306
  • 32
  • 90
  • 132

14 Answers14

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

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

/sdcard/YourCustomDirectory/ExampleFile.mp3

Niko Gamulin
  • 66,025
  • 95
  • 221
  • 286
  • I think Inner children are not deleted.. you have to delete all inner childs.See my answer below.. – Zar E Ahmer May 15 '14 at 07:56
  • 3
    Unfortunately this won't work on Android 4.4+. See my answer below. – stevo.mit May 20 '14 at 13:44
  • I don't understand how did this work for many. "deleted" looks greyed out in Android Studio. – TheOnlyAnil Jun 06 '15 at 11:18
  • yeah i was sending path like "file:///storage/..." which did not work – Jemshit Aug 03 '15 at 09:02
  • You need context.sendBroadcast(). See my answer – Jiyeh Jan 11 '16 at 02:56
  • This returns false when deleting image file from DCIM folder in SD card. – Jay Donga Feb 04 '16 at 14:56
  • 1
    @stevo.mit did you find the solution? I am also facing the same problem can't delete file from sdcard above Android 4.4+. But the same code working for 4.3/ – hasnain_ahmad Jul 18 '16 at 12:31
  • don't use SD Card for Phone storage these days, SD Card is an external memory card (MicroSD Card) and you are not allowed to write there in Android using `File` (only read), so your code won't work (you won't be able to delete files using `File.delete()` method) – user25 May 27 '18 at 00:38
  • This answer needs to be updated as it won't work on Android 4.4+ – Spikatrix Jul 03 '18 at 13:14
79

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

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

in AndroidManifest.xml file

GAMA
  • 5,958
  • 14
  • 79
  • 126
neeloor2004
  • 791
  • 5
  • 2
37

Change for Android 4.4+

Apps are not allowed to write (delete, modify ...) to external storage except to their package-specific directories.

As Android documentation states:

"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 workaround exists (see code below). Tested on Samsung Galaxy S4, but this fix does't work on all devices. Also I wouldn’t count on this workaround being available in future versions of Android.

There is a great article explaining (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; 
   } 
}
stevo.mit
  • 4,681
  • 4
  • 37
  • 47
18

Android Context has the following method:

public abstract boolean deleteFile (String name)

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

Yossi
  • 1,226
  • 1
  • 16
  • 31
11

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();
}
Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
  • There are some changes since Android KitKat. Future readers might use the link below as an one of sources for references: https://stackoverflow.com/questions/45253756/cant-delete-file-from-external-storage-in-android-programmatically – Gleichmut Jul 29 '23 at 11:26
9

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))));
Jiyeh
  • 5,187
  • 2
  • 30
  • 31
  • 2
    What does context.sendBroadcast() do? – Megaetron Dec 01 '15 at 09:47
  • Basically, it sends/broadcasts the intent (operation to be performed) to all receivers matching this Intent. [link](http://developer.android.com/reference/android/content/Context.html) – Jiyeh Dec 01 '15 at 10: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());
 }

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

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Vivek Elangovan
  • 238
  • 2
  • 16
  • files[] can be null if: `file.exists:true file.isDirectory:true file.canRead:false file.canWrite:false` – ilw Jun 04 '17 at 14:13
  • I guess you guys are completely unaware that some android phones restrict write access to sd cards. –  Sep 20 '19 at 05:52
4

Try this.

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

from Apache Commons

Rahul Giradkar
  • 1,818
  • 1
  • 17
  • 28
1

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...

Blindman67
  • 51,134
  • 11
  • 73
  • 136
Denis IJCU
  • 11
  • 1
1

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

I renamed the files and ignored them in my application.

ie.

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

This worked for me.

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

String my_Path = Environment.getExternalStorageDirectory()+myFile;  

File f = new File(my_Path);
Boolean deleted = f.delete();
aweigold
  • 6,532
  • 2
  • 32
  • 46
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

You can delete a file as follow:

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());
  }
}
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
Makvin
  • 3,475
  • 27
  • 26
-1
File filedel = new File("/storage/sdcard0/Baahubali.mp3");
boolean deleted1 = filedel.delete();

Or, Try This:

String del="/storage/sdcard0/Baahubali.mp3";
File filedel2 = new File(del);
boolean deleted1 = filedel2.delete();
Satan Pandeya
  • 3,747
  • 4
  • 27
  • 53
  • 1
    Both your examples are pretty much the same. Also, the highest voted answer tells exactly to do this. Can't see what more this answer adds the question. Also, this will not work for files in an external storage (like SD card) from Android Kitkat onwards IIRC – Spikatrix Jul 03 '18 at 12:05