How to delete a file in JavaThere are two methods to delete a file in Java:
Java File.delete() methodIn Java, we can delete a file by using the File.delete() method of File class. The delete() method deletes the file or directory denoted by the abstract pathname. If the pathname is a directory, that directory must be empty to delete. The method signature is: The method returns true if the file or directory deleted successfully, otherwise returns false. ExampleOutput: When the file exist. ![]() When the file does not exist. ![]() Java File.deleteOnExit() methodThe File.deleteOnExit() method also deletes the file or directory defined by abstract pathname. The deleteOnExit() method deletes file in reverse order. It deletes the file when JVM terminates. It does not return any value. Once the request has been made, it is not possible to cancel the request. So this method should be used with care. The method signature is: Usually, we use this method when we want to delete the temporary file. A temporary file is used to store the less important and temporary data, which should always be deleted when JVM terminates. If we want to delete the .temp file manually, we can use File.delete() method. ExampleThe following example creates a temporary file named abc.temp and delete it when the program is terminated. Output: ![]() Let's see another example that deletes text file. ExampleOutput: ![]()
Next TopicJava Tutorial
|
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week