空目录不在android中删除

时间:2013-12-30 09:40:07

标签: android file

任何人都可以告诉为什么这段代码不能用于删除空目录,即使path.exists()返回true但没有执行删除操作..

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    File file = new File(Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/directoryName");
    boolean isDeleted = deleteDirectory(file);
    System.out.println(isDeleted);
}

static public boolean deleteDirectory(File path) {
    if (path.exists()) {
        System.out.println("MainActivity.deleteDirectory()");
        File[] files = path.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                deleteDirectory(files[i]);
            } else {
                files[i].delete();
            }
        }
    }
    return (path.delete());
}

1 个答案:

答案 0 :(得分:2)

将序列改为:

boolean deleteDirectory(File path) {
    if(path.exists()) {
        if (path.isDirectory()) {
            File[] files = path.listFiles();
            for (int i=0; i<files.length; i++) {
                deleteDirectory(files[i]);
            }
        }
        return path.delete();
    }

    return false;
}

记得申请许可:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />