Delete or Rename File in Java

In the tutorials we will see, How can we Delete or rename the file using Java.

In previous tutorials, We have seen, how can we create, write and save a file in Java. In this tutorial, First we will see, how can we delete the file using Java.


Delete File in Java:

To delete the file we can use the method delete() present within the File class. The same method can be used to delete a director provided it but the only condition is directory should be empty.

This method returns: true if the file exists and deleted successfully and false otherwise. Let’s see the example of file delete in Java –

The above code will delete the named SampleWriterFile If present at the given location else it will print the exception message.


Rename File in Java:

To rename the file we can use the method renameTo() , present within the File class. However , this method is really platform-dependent: you may successfully rename a file in *nix but failed in Windows. So, the return value (true if the file rename successful, false if failed) should always be checked to make sure the file is renamed successfully.

The above code will rename the file name. It will rename the file named TestFile to TestFile10 .

You can copy and try the above both classes on your local machine and practice to delete the directory. First, create then delete a file and other scenarios as well.

0 Comment

Leave a Reply