Deleting file from sdcard in android

2019-02-24 15:04发布

问题:

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.

回答1:

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();


回答2:

**try this method :

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());
}

or you can use the following code to delete the file from sd-card:

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

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


回答3:

Try this

  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();

  }


回答4:

try this too:

  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 );

that code you can see the latest file saved in sdcard, i suggest you to follow along this tutorial.