Search code examples
androidfilesd-carddelete-file

Deleting file from sdcard in android


I am making an app in which I have to delete the recently added mp3 file in sdcard. The format in which the song is saved is:

Songhello_17_26.amr

where 17_26 is the time when song was added. Can anyone help me how delete the recently added file in sdcard. I mean to say that I want to delete the time means the latest added file should get deleted. Any help will be appreciated.


Solution

  • As it states here, you cant do that directly, you first need to get list of files File.listFiles(), Comparator,File.lastModified(), Arrays.sort() and delete.

    Edited:

    File f = new File(path);
    
    File [] files = f.listFiles();
    
    Arrays.sort( files, new Comparator()
    {
        public int compare(Object o1, Object o2) {
    
            if (((File)o1).lastModified() > ((File)o2).lastModified()) {
                return -1;
            } else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
                return +1;
            } else {
                return 0;
            }
        }
    
    }); 
    

    To delete latest one:

     files[0].delete();