---
# System prepended metadata

title: 刪除image file
tags: [IO相關]

---

刪除image file
===

```java=
  private void deleteImage(File file) {
       
        // Query for the ID of the media matching the file path
        ContentResolver contentResolver = getContentResolver();
        
        Cursor c = contentResolver.query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
            new String[]{ MediaStore.Images.Media._ID }, 
            MediaStore.Images.Media.DATA + " = ?", 
            new String[]{ file.getAbsolutePath() }, 
            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();
    }
```

[Delete image file from device programmatically](https://stackoverflow.com/questions/39530663/delete-image-file-from-device-programmatically)

###### tags: `IO相關`