In this example we are discussing the deletion of a file or a directory by using a java program.In this example we are discussing the deletion of a file or a directory by using a java program.
In this example we are discussing the deletion of a file or a directory by using a java program. We pass the file name or the directory name to which we want to delete. The given program deletes an existing file if the file is not write protected. this example also deletes an existing directory if the directory is empty otherwise delete operation fails.
Description of program:
In the given example first of all we check the string array variable str for its length, if we pass a command line argument then its value will not be null and rest of the operation is performed. After that we are creating a delete() method. In this method first we are creating a file object that contains the file or directory name to be deleted. Then we check for file whether it exists or not and if it exists checks whether it is write protected or not and calls the delete() on this file, If it is not a file then we check for the directory and also checks whether it is empty or not and after that we are calling the delete() method on this object and takes the result in a Boolean type variable success. If this variable has the value true then the given directory is deleted successfully otherwise If condition gets executed and the message Deletion: deletion failed is displayed. In our case we are creating a directory named delte that is not empty and then we are trying to delete it, thats why we got the message Can not delete as directory is not empty: delte.
Here is the code of this program:
Here is the output:
|C:\Examples>java DeleteOperation delte
Can not delete as directory is not empty: delte