简体   繁体   中英

How to delete all files in a directory java android app? Current code is deleting the that folder

This is my code

private final static String Dir = "/data/data/org.xbmc.kodi/cache/";
private void deleteDir(){
    try{
        /*File dir = Utils.getCacheDir(null, this, false, true);
        File path = new File(dir.getParentFile(), Dir);
        delete(path);*/
        String command = "rm -r "+Dir;
        Process process = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(process.getOutputStream());
        os.writeBytes(command + "\n");
        os.writeBytes("exit\n");
        os.flush();
        process.waitFor();
    }catch(Exception e){}
}

The issue is when I run this it deletes the folder. But I don't want to delete the folder. I want to delete all the files inside it.

Use this:

File file = new File("your dir");        
String[] files;      
files = file.list();  
for (int i=0; i<files.length; i++) {  
    File myFile = new File(file, files[i]);   
    myFile.delete();  
} 
File dir = new File(Environment.getExternalStorageDirectory()+"Dir_name_here"); 
if (dir.isDirectory()) 
{
    String[] children = dir.list();
    for (int i = 0; i < children.length; i++)
    {
       new File(dir, children[i]).delete();
    }
}

source thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM