Como é que apago os ficheiros programaticamente no Android?

estou no 4.4.2, a tentar apagar um ficheiro (imagem) através do uri. Aqui está o meu código:

File file = new File(uri.getPath());
boolean deleted = file.delete();
if(!deleted){
      boolean deleted2 = file.getCanonicalFile().delete();
      if(!deleted2){
           boolean deleted3 = getApplicationContext().deleteFile(file.getName());
      }
}

neste momento, nenhuma destas funções de remoção está realmente a apagar o ficheiro. Também tenho isto no meu teste AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
Author: Brian Tompsett - 汤莱恩, 2014-07-09

4 answers

Porque não testa isto com este código:

File fdelete = new File(uri.getPath());
if (fdelete.exists()) {
    if (fdelete.delete()) {
        System.out.println("file Deleted :" + uri.getPath());
    } else {
        System.out.println("file not Deleted :" + uri.getPath());
    }
}

Eu acho que parte do problema é que você nunca tentar apagar o arquivo, você apenas continua criando uma variável que tem uma chamada de método.

Então, no seu caso, pode tentar:

File file = new File(uri.getPath());
file.delete();
if(file.exists()){
      file.getCanonicalFile().delete();
      if(file.exists()){
           getApplicationContext().deleteFile(file.getName());
      }
}
No entanto, acho que isso é um pouco exagerado.

Adicionou um comentário que está a usar uma pasta externa em vez de um uri. Então, em vez disso, você deve adicionar algo como:

String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/images/media/2918"); 

Depois tente apagar o ficheiro.

 70
Author: Shawnic Hedgehog, 2017-02-12 08:57:40
Experimenta este. Está a funcionar para mim.
handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                // Set up the projection (we only need the ID)
                                String[] projection = { MediaStore.Images.Media._ID };

// Match on the file path
                                String selection = MediaStore.Images.Media.DATA + " = ?";
                                String[] selectionArgs = new String[] { imageFile.getAbsolutePath() };

                                // Query for the ID of the media matching the file path
                                Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                                ContentResolver contentResolver = getActivity().getContentResolver();
                                Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
                                if (c.moveToFirst()) {
                                    // We found the ID. Deleting the item via the content provider will also remove the file
                                    long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
                                    Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
                                    contentResolver.delete(deleteUri, null, null);
                                } else {
                                    // File not found in media store DB
                                }
                                c.close();
                            }
                        }, 5000);
 13
Author: Krishna, 2015-01-19 11:21:44
Testei este código no emulador de Nougat e funcionou.

Em adição manifesta:

<application...

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>

Crie uma pasta xml vazia na pasta res e no passado nas vias provider_ Path.xml:

<?xml version="1.0" encoding="utf-8"?>
 <paths xmlns:android="http://schemas.android.com/apk/res/android">
   <external-path name="external_files" path="."/>
  </paths>

Depois coloque o próximo trecho no seu código (por exemplo, fragmento):

File photoLcl = new File(homeDirectory + "/" + fileNameLcl);
Uri imageUriLcl = FileProvider.getUriForFile(getActivity(), 
  getActivity().getApplicationContext().getPackageName() +
    ".provider", photoLcl);
ContentResolver contentResolver = getActivity().getContentResolver();
contentResolver.delete(imageUriLcl, null, null);
 4
Author: CodeToLife, 2017-06-06 11:55:20
Vejo que encontraste a tua resposta, mas não resultou comigo. Delete continuou retornando falso, então eu tentei o seguinte e funcionou (para qualquer outra pessoa para quem a resposta escolhida não funcionou):
System.out.println(new File(path).getAbsoluteFile().delete());
{[[2]} o sistema pode ser ignorado obviamente, eu pu-lo para conveniência de confirmar a eliminação.
 1
Author: Arijit, 2015-05-27 04:39:57