javaandroidfile-manager

How can I delete an external folder with Android?


I have been searching for it but theres no any answer to my problem. I am programming an app and I want to delete an external folder. For example /storage/emulated/0/MyFolder, there is a lot of ways to create and read files from a internal app folder and an external app folder, but I dont know how to acces to files in "/storage/emulated/0/...".

Thanks.


Solution

  •   public static void deleteDir(Context ctx) {
    
            try {
                File myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                                    + File.separator
                                    + "MyFolder");
                }
                if (myFile.exists()) {
                    deleteRecursive(myFile);
                }
            }catch (Exception ignored){
                Log.e("Delete error File: %s",ignored.getMessage());
            }
        }
    
        private static void deleteRecursive(File myFile) {
            if (myFile.isDirectory())
                for (File child : myFile.listFiles())
                    deleteRecursive(child);
            Log.e("MyFolder Files Deleted!!! : %s", myFile.delete());
        }
    

    Update - As mentioned by CommonsWare runtime permission request needed for Android 6+

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
        } else {
            deleteDir(context);
        }
    

    Your Activity

      @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            switch (requestCode) {
                case 101:
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        deleteDir(context);
                    }
            }
        }