Skip to main content

Java Program to delete any file or directory

The following code is to delete any file or directory and all of its contents. The deleted file or directory will be deleted permanently same as using SHIFT+DEL keys.
Code:-

import java.io.*;
import java.nio.file.*;
import java.util.*;
public class Delete {
    Scanner scan = new Scanner(System.in);
    String pth;
    char ch;
    boolean empty;
    public void input() {
        try {
            System.out.printf("PATH: ");
            pth = scan.nextLine();
        } catch (InputMismatchException e) {
            System.err.println("Error Occur!\n" + e.getMessage());
            System.exit(0);
        }
    }
    public void check(Path delPath) {
        try {
            if (Files.isHidden(delPath)) {
                System.out.println("Path Leads To An Hidden File/Directory!");
                System.out.printf("Still Wanna Continue Y/N? ");
                pth = scan.next();
                ch = pth.charAt(0);
                pth = Character.toString(ch);
            }
            if (Files.notExists(delPath)) {
                System.err.println("Invalid Path!");
                System.exit(0);
            }
            if (pth.equalsIgnoreCase("N")) {
                System.out.println("You chose not to continue!");
                System.exit(0);
            }
        } catch (Exception e) {
            System.err.println("Error Occur!\n" + e.getMessage());
            System.exit(0);
        }
    }
    public void compute(Path delPath) {
        check(delPath);
        boolean deleted;
        try {
            delPath = Paths.get(pth);
            deleted = Files.deleteIfExists(delPath);
            if (deleted == true) {
                System.out.println("RESULT: DELETED!");
                System.exit(0);
            } else {
                System.out.println("RESULT: NOT DELETED!");
                System.exit(0);
            }
        } catch (DirectoryNotEmptyException e) {
            System.out.println("Error Occur!\n" + e.getMessage());
            empty = false;
        } catch (IOException e) {
            System.err.println("Error Occured!\n" + e.getMessage());
            System.exit(0);
        } finally {
            try {
                if (empty == false) {
                    System.out.printf("PERMISSION: DIRECTORY NOT EMPTY CONTINUE Y/N? ");
                    pth = scan.next();
                    ch = pth.charAt(0);
                    pth = Character.toString(ch);
                    if (pth.equalsIgnoreCase("N")) {
                        System.out.println("You chose not to continue!");
                        System.exit(0);
                    }
                    File delFolder = new File(delPath.toString());
                    deleted = deleteNonEmptyDir(delFolder);
                    if (deleted == true) {
                        System.out.println("RESULT: DELETED!");
                    } else {
                        System.exit(0);
                    }
                }
            } catch (Exception e) {
                System.err.println("Error Occur!\n" + e.getMessage());
                System.exit(0);
            }
        }
    }
    public boolean deleteNonEmptyDir(File dir) {
        try {
            String[] list = dir.list();
            for (int i = 0; i < list.length; i++) {
                File temp = new File(dir.getAbsolutePath() + "\\" + list[i]);
                boolean del = temp.delete();
                if (del == false) {
                    boolean success = deleteNonEmptyDir(new File(dir, list[i]));
                    if (!success) {
                        return false;
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("Error Occur!\n" + e.getMessage());
            System.exit(0);
        }
        return dir.delete();
    }
    public static void main(String[] args) {
        Delete del = new Delete();
        del.input();
        Path p = Paths.get("C:\\");
        del.compute(p);
    }
}

Comments

Popular posts from this blog

Java Program to calculate the Run Rate per over in a cricket match

import java.io.*; import java.util.*; public class RunRate{     Scanner scan=new Scanner(System.in);     int runs, balls;     float runRate;     public void input(){         try{             System.out.println("Enter Runs Scored: ");             runs=scan.nextInt();             System.out.println("Enter Balls Delivered: ");             balls=scan.nextInt();         }         catch(NumberFormatException e){             System.out.println("Error Code: "+e);             System.exit(0);   ...

Vanilla Javascript each()

JQuery's each() is very useful when iterating through elements. But you don't want to use JQuery in your project you can simply add the following javascript code which works somewhat similar to the JQuery's each function. Here the fnc parameter is the function string which is converted to a valid function call replacing all the $(this) with this /**  * This function binds a particular function to every element with the specified selector. It is somewhat same as JQuery's each() with less functionality  * @param {String|DOMElement} selector  * @param {Function} fnc  */ function each(selector, fnc) {     var elem;     if (typeof selector === "string") {         elem = $_(selector);     } else {         elem = selector;     }     fnc = (fnc.toString().replace("$(this)", "elem") + "();").replace("function () {", "").replac...

Java Program to display Welcome Message

import java.io.*;// I/O package imported. public class Welcome{        //class name is "Welcome"     public Welcome(){      //constructor declaired to print the message.         System.out.println("Welcome to Java Programming Language!");/* System.out.println is used for output. Welcome Message is written within " ".*/     }//display() closes here.     public static void main(String[] args){        //main() is declaired to declair an object in it.         Welcome obj=new Welcome();  //Object "Obj" is bean created.     }//main() closes. }//class "Welcome" ends here. Above program displays the message which is written by you in " ".  In programs "/*" and "*/" are use for multiple line comment(s) and "//" is use for single line comment. Code line "Welc...