Delete file from internal storage

前端 未结 8 1618
借酒劲吻你
借酒劲吻你 2020-11-30 00:28

I\'m trying to delete images stored in internal storage. I\'ve come up with this so far:

File dir = getFilesDir();
File file = new File(dir, id+\".jpg\");
bo         


        
相关标签:
8条回答
  • 2020-11-30 00:38

    The getFilesDir() somehow didn't work. Using a method, which returns the entire path and filename gave the desired result. Here is the code:

    File file = new File(inputHandle.getImgPath(id));
    boolean deleted = file.delete();
    
    0 讨论(0)
  • 2020-11-30 00:45

    Have you tried Context.deleteFile() ?

    0 讨论(0)
  • 2020-11-30 00:45

    This is an old topic, but I will add my experience, maybe someone finds this helpful

    >     2019-11-12 20:05:50.178 27764-27764/com.strba.myapplicationx I/File: /storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/JPEG_20191112_200550_4444350520538787768.jpg//file when it was created
    
    2019-11-12 20:05:58.801 27764-27764/com.strba.myapplicationx I/File: content://com.strba.myapplicationx.fileprovider/my_images/JPEG_20191112_200550_4444350520538787768.jpg //same file when trying to delete it
    

    solution1:

                  Uri uriDelete=Uri.parse (adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ());//getter getImageuri on my object from adapter that returns String with content uri
    

    here I initialize Content resolver and delete it with a passed parameter of that URI

                ContentResolver contentResolver = getContentResolver ();
                contentResolver.delete (uriDelete,null ,null );
    

    solution2(my first solution-from head in this time I do know that ): content resolver exists...

                  String path = "/storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/" +
                        adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ().substring (58);
    
                File file = new File (path);
                if (file != null) {
                    file.delete ();
                }
    

    Hope that this will be helpful to someone happy coding

    0 讨论(0)
  • 2020-11-30 00:49

    This works for me:

    Java

    File file = new File(photoPath);
    file.delete();
    
    MediaScannerConnection.scanFile(context,
                    new String[]{file.toString()},
                    new String[]{file.getName()},null);
    

    Kotlin

    val file = File(photoPath) 
    file.delete()
    
    MediaScannerConnection.scanFile(context, arrayOf(file.toString()),
          arrayOf(file.getName()), null)
    
    0 讨论(0)
  • 2020-11-30 00:51

    Have you tried getFilesDir().getAbsolutePath()?

    Seems you fixed your problem by initializing the File object with a full path. I believe this would also do the trick.

    0 讨论(0)
  • 2020-11-30 00:54

    You can also use: file.getCanonicalFile().delete();

    0 讨论(0)
提交回复
热议问题