Delete file from sdcard in android

I am creating an application in which I need to delete a newly added mp3 file in sdcard. Song save format:

Songhello_17_26.amr

where 17_26 is the time the song was added. Can someone help me how to delete a recently added file in sdcard. I want to say that I want to delete the time, because the last file added must be deleted. Any help would be appreciated.

+3
source share
4 answers

As indicated here, you can not do it directly, you first need to get a list of files File.listFiles(), Comparator, File.lastModified(), Arrays.sort()and remove.

Edited by:

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 uninstall the latest version:

 files[0].delete();
+6
source

** :

public static boolean deleteDirectory(File path) {
    // TODO Auto-generated method stub
    if( path.exists() ) {
        File[] files = path.listFiles();
        for(int i=0; i<files.length; i++) {
    enter code here        if(files[i].isDirectory()) {
                deleteDirectory(files[i]);
            }
            else {
                files[i].delete();
            }
        }
    }
    return(path.delete());
}

SD-:

File folder = Environment.getExternalStorageDirectory(); String fileName = folder.getPath() + "/pass/hello.pdf";

 String fileName = Environment.getExternalStorageDirectory() + "/pass/hello.pdf";**
+3

try it

  public String[] getDirectoryList(String path) {
     String[] dirListing = null;
     File dir = new File(path);
     dirListing = dir.list();

     Arrays.sort(dirListing, 0, dirListing.length);
     return dirListing;
  }

  String[]  lstFile = getDirectoryList()
 if(lstFile.length > 0){
    File file = new File(lstFile[0]);
    boolean fStatus = file.delete();

  }
+2
source

try also:

  String root_sd = Environment.getExternalStorageDirectory().toString();
 File file = new File(path) ;       
  File list[] = file.listFiles();
    for(File f:list)
      {
     name =  file.getName();
    filestv.setText(f.getName());
    //add new files name in the list
   //  delete.setText(name );

In this code, you can see the last file saved in sdcard, I suggest you follow this tutorial .

0
source

All Articles