0

Am using this code for deleting the specific file in all directories and sub directorates in a drive but its not working. please help me in this regard. If i want to delete the specific file in all drives how to do.

   static String refile= "input.txt";   
   public static void deletemyfile(File directory) {
    if (directory.exists()) {
           File[] files = directory.listFiles();
           if (null != files) {
                 for (int i = 0; i < files.length; i++) {
                        System.out.println(files[i].getName());
                        if (files[i].isDirectory()) {
                               deletemyfile(files[i]);

                        } else  { 

                            String temp ;
                            temp = files[i].getName();                              
                            if (temp==refile){

                            System.out.println("name matched and about to delete");

                            (files[i]).delete();


                        } else{

                            System.out.println("name not matched");
                        }



                        }
                 }
           }
    } else {System.out.println("wrong path");
    }
  }
karthik
  • 1
  • 2

1 Answers1

0

Try using Java 8 for your solution. The following will walk through all sub-directories from the given directory and delete all files that match the given filename.

public static void deleteMyFile(File directory, String filename) {
    if(directory.isDirectory()) {
        try {
            Files.walk(directory.toPath())
                .filter(path -> path.getFileName().toString().equals(filename))
                .forEach(path -> path.toFile().delete());
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}
eighthrazz
  • 331
  • 1
  • 6