0

I'm very new in Java and I'd like to know if there's any way to delete a folder that may contain some files just like "rm -rf directory/" in command line.

Here's what I'm working on.

public static boolean checkUnzippedExistence(String deleteKeyword) {
    List<String> foldersList = new ArrayList<String>();
    String absPath = Environment.getExternalStorageDirectory().getPath();
    File[] files = new File(absPath).listFiles();
    boolean existence = false;
    if (files != null) {
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory() && files[i].getName().contains(deleteKeyword)) {
                //some method/function to delete
            }
        }
        existence = true;
    }
    return existence;
}

Thanks in advance.

2 Answers 2

1

You can use Apache Commons FileUtils. It contains great utility methods that you can use for file operations:

Gradle dependency for Apache Commons:

compile group: 'commons-io', name: 'commons-io', version: '2.4'
2
  • Looks good! But your Gradle dependency was incorrect since it does not include FileUtils... mvnrepository.com/artifact/commons-io/commons-io
    – inductor
    Aug 8, 2017 at 4:46
  • Sorry about that. I edited my answer. Here's the correct one: compile group: 'commons-io', name: 'commons-io', version: '2.4'
    – ABS
    Aug 8, 2017 at 5:12
0

Below code will help you to identify whether given file matches with your condition.

public static boolean checkUnzippedExistence(String deleteKeyword) {
    List<String> foldersList = new ArrayList<String>();
    String absPath = Environment.getExternalStorageDirectory().getPath();
    File[] files = new File(absPath).listFiles();
    deleteDirectory(files)
}



private boolean deleteDirectory(File[] files) {
      if (files == null) {
          return true;
      }
      for(int i=0; i<files.length; i++) {
         if(files[i].isDirectory()) {
           deleteDirectory(files[i]);
         }
         else {
           files[i].delete();
         }
      }
    }
    return( path.delete() );
  }
2
  • Thanks! I'll have a look if this will fit for our precise condition!
    – inductor
    Aug 8, 2017 at 5:08
  • deleteDirectory(files[i]); cannot be "File" with this context, it seems
    – inductor
    Aug 8, 2017 at 6:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.