How to delete a file from SD card?

2019-01-01 00:11发布

I am creating a file to send as an attachment to an email. Now I want to delete the image after sending the email. Is there a way to delete the file?

I have tried myFile.delete(); but it didn't delete the file.


I'm using this code for Android, so the programming language is Java using the usual Android ways to access the SD card. I am deleting the file in the onActivityResult method, when an Intent is returned to the screen after sending an email.

14条回答
浪荡孟婆
2楼-- · 2019-01-01 00:52

You can delete a file as follow:

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());
  }
}
查看更多
何处买醉
3楼-- · 2019-01-01 00:54

This worked for me.

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

String my_Path = Environment.getExternalStorageDirectory()+myFile;  

File f = new File(my_Path);
Boolean deleted = f.delete();
查看更多
春风洒进眼中
4楼-- · 2019-01-01 00:57
File filedel = new File("/storage/sdcard0/Baahubali.mp3");
boolean deleted1 = filedel.delete();

Or, Try This:

String del="/storage/sdcard0/Baahubali.mp3";
File filedel2 = new File(del);
boolean deleted1 = filedel2.delete();
查看更多
若你有天会懂
5楼-- · 2019-01-01 00:58

Also you have to give permission if you are using >1.6 SDK

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

in AndroidManifest.xml file

查看更多
浪荡孟婆
6楼-- · 2019-01-01 00:58

I had a similar issue with an application running on 4.4. What I did was sort of a hack.

I renamed the files and ignored them in my application.

ie.

File sdcard = Environment.getExternalStorageDirectory();
                File from = new File(sdcard,"/ecatAgent/"+fileV);
                File to = new File(sdcard,"/ecatAgent/"+"Delete");
                from.renameTo(to);
查看更多
有味是清欢
7楼-- · 2019-01-01 01:00

This works for me: (Delete image from Gallery)

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

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(photoPath))));
查看更多
登录 后发表回答