2014-07-09 15 views
20

Jestem na 4.4.2, próbuję usunąć plik (obraz) za pomocą URI. Oto mój kod:Jak programowo usuwać pliki w systemie Android?

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

W tej chwili żadna z tych funkcji usuwania nie usuwa pliku. Ja również mam to w moim 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" /> 
+0

Nie używam getCanonicalFile(), ale tylko File.delete() i działa dobrze na moim systemie. O ile Twoja ścieżka z URI nie jest poprawna. –

+0

Moja ścieżka jest następująca: /external/images/media/2918 Czy to wygląda prawidłowo? –

+0

... nie. coś takiego jak '/ mnt/sdcard/your_folder/your_file.png' robi. Jednak lepiej jest uzyskać ścieżkę zapisu przez 'getExternalDirectory'. Ostatnie, uprawnienie 'WRITE_EXTERNAL _...' zawiera 'READ_EXTERNAL _...' one. –

Odpowiedz

55

Dlaczego nie przetestować to z tym kodem:

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

myślę częścią problemu jest nie spróbować usunąć plik, po prostu nadal tworzysz zmienną, która ma wywołanie metody.

Więc w twoim przypadku można spróbować:

File file = new File(uri.getPath()); 
file.delete(); 
if(file.exists()){ 
     file.getCanonicalFile().delete(); 
     if(file.exists()){ 
      getApplicationContext().deleteFile(file.getName()); 
     } 
} 

Jednak myślę, że to trochę przesada.

Dodałeś komentarz, że korzystasz z zewnętrznego katalogu zamiast URI. Zamiast tego należy dodać coś takiego:

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

Następnie spróbuj usunąć plik.

+0

Myślę, że możesz być na czymś. ciągle powtarza, że ​​fdelete nie istnieje. Moja ścieżka do pliku to/external/images/media/2918. Czy to wygląda dobrze? –

+0

Nie sądzę, aby twoje rozwiązanie działało w jego przypadku, ponieważ robi to już tak, jak mu kazałeś. – migos

+0

brak sufiksu, takiego jak * .png lub * .jpg? – migos

12

Wypróbuj tę. To działa dla mnie.

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

pracuje dla mnie thk – Guihgo

0

Widzę, że znalazłeś odpowiedź, ale nie dla mnie. Usuń powracał fałszywe, więc próbowałem następujące i to działało (dla kogoś innego, dla którego wybrana odpowiedź nie działa):

System.out.println(new File(path).getAbsoluteFile().delete()); 

System out mogą być ignorowane oczywiście, umieścić go dla wygody potwierdzający usunięcie.

2

testowałem ten kod na nugat emulatora i to działało:

W oczywisty dodają:

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

Tworzenie pustego folderu xml w folderze res i przeszłości w provider_paths.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> 

Następnie umieść następny fragment kodu (na przykład fragment):

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); 
Powiązane problemy