How to Delete a file

In this blog post, I will be demonstrating how you can delete a file in Java. Consider the following code snippet:

package learnjava.io;import java.io.File;public class DeleteFile {public static void main(String[] args) {String fileName = "D:/Test.txt";File file = new File(fileName);if (file.exists()) {if (file.delete()) {System.out.println("Deleted file successfully");} elseSystem.out.println("Error in deleting file");} elseSystem.out.println("File is missing, so could not be deleted");}}

 

There is a File.delete method available to delete a file. It returns true, if the delete was successful, otherwise returns a false. So if you run the above code snippet, the following output will be printed (Assuming there is a file called test.txt on D Drive):

 

Deleted file successfully

Comments

Popular posts from this blog

How to use logging in SpringBoot with code samples

Python While Loop with code samples

How to convert a List to a Set