Cómo eliminar un archivo de la tarjeta SD?


Estoy creando un archivo para enviar como archivo adjunto a un correo electrónico. Ahora quiero eliminar la imagen después de enviar el correo electrónico. ¿Hay alguna forma de eliminar el archivo?

He intentado myFile.delete(); pero no eliminar el archivo.


Estoy usando este código para Android, por lo que el lenguaje de programación es Java utilizando las formas habituales de Android para acceder a la tarjeta SD. Estoy borrando el archivo en el método onActivityResult, cuando se devuelve un Intent a la pantalla después de enviar un correo electrónico.

Author: Michael Celey, 2009-08-08

14 answers

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

Donde selectedFilePath es la ruta del archivo que desea eliminar, por ejemplo:

/ sdcard/YourCustomDirectory / ExampleFile.mp3

 352
Author: Niko Gamulin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-10 09:14:48

También tiene que dar permiso si está utilizando >1.6 SDK

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

En AndroidManifest.xml archivo

 79
Author: neeloor2004,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-23 11:23:57

Cambiar para Android 4.4 +

Las aplicaciones no están permitidas para escribir (borrar, modificar ...) to external storage except to their package-specific directories.

Como dice la documentación de Android:

" No se debe permitir que las aplicaciones escriban en almacenamiento externo secundario dispositivos, excepto en sus directorios específicos del paquete, según lo permitido por permisos sintetizados."

Sin Embargo desagradable existe una solución alternativa (véase el código a continuación). Probado en Samsung Galaxy S4, pero esta solución no funciona en todos los dispositivos. También yo no contaría con esta solución alternativa está disponible en futuras versiones de Android.

Hay un gran artículo explicando (4.4+) cambio de permisos de almacenamiento externo.

Puede leer más información sobre la solución aquí. El código fuente es de este sitio.

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; 
   } 
}
 33
Author: stevo.mit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-20 20:59:16

El contexto de Android tiene el siguiente método:

public abstract boolean deleteFile (String name)

Creo que esto hará lo que quieras con las premisiones de la aplicación correcta como se indica anteriormente.

 16
Author: Yossi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-30 13:03:55

Elimina recursivamente todos los hijos del archivo ...

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

        fileOrDirectory.delete();
    }
 11
Author: Xar E Ahmer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-15 07:57:15

Esto funciona para mí: (Eliminar imagen de la galería)

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

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(photoPath))));
 9
Author: Jiyeh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-16 11:47:59
 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());
 }

Este Código te ayudará.. Y en Android Manifest Tienes que obtener Permiso para hacer modificaciones..

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 6
Author: Vivek Elangovan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-07 12:35:20

Prueba esto.

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

De Apache Commons

 4
Author: Rahul Giradkar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-27 05:01:26

Lo sentimos: Hay un error en mi código anterior debido a la validación del sitio.

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

String myPath = Environment.getExternalStorageDirectory()+myFile;  

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

Creo que está claro... Primero debe conocer la ubicación de su archivo. En segundo lugar,,, Environment.getExternalStorageDirectory() es un método que obtiene el directorio de la aplicación. Por último, el Archivo de clase que maneja su archivo...

 1
Author: Denis IJCU,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-02 04:46:27

Tuve un problema similar con una aplicación que se ejecuta en 4.4. Lo que hice fue una especie de hackeo.

Cambié el nombre de los archivos y los ignoré en mi aplicación.

Ie.

File sdcard = Environment.getExternalStorageDirectory();
                File from = new File(sdcard,"/ecatAgent/"+fileV);
                File to = new File(sdcard,"/ecatAgent/"+"Delete");
                from.renameTo(to);
 1
Author: kkm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-14 12:58:15

Esto funcionó para mí.

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

String my_Path = Environment.getExternalStorageDirectory()+myFile;  

File f = new File(my_Path);
Boolean deleted = f.delete();
 0
Author: Denis IJCU,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-07 17:22:37
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
Author: Lâm Nguyễn Tuấn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-13 14:38:34

Puede eliminar un archivo de la siguiente manera:

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());
  }
}
 0
Author: Makvin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-23 15:58:12
File filedel = new File("/storage/sdcard0/Baahubali.mp3");
boolean deleted1 = filedel.delete();

O, Prueba Esto:

String del="/storage/sdcard0/Baahubali.mp3";
File filedel2 = new File(del);
boolean deleted1 = filedel2.delete();
 -1
Author: Laxman Ghuge,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-02 11:36:45