Write a java program to Delete a file


This Java code defines a class Delete_File with a main method that deletes a file named "file.txt" in the current working directory if it exists.

The try block creates a new File object using the fileName string, and then checks if the file exists using the exists method of the File class. If the file exists, the program attempts to delete the file using the delete method. If the deletion is successful, the program prints out a message indicating that the file has been deleted. If the deletion fails, the program prints out a message indicating that the file deletion failed. If the file does not exist, the program prints out a message indicating that the file does not exist.

Note that this code assumes that the file "file.txt" exists in the current working directory, and will not throw an error if the file does not exist.

Source Code

import java.io.File;
public class Delete_File
{
	public static void main(String args[])
	{
		final String fileName = "file.txt";
		File obj = new File(fileName);
 
		//check file is exist or not, if exist delete it
		if (obj.exists() == true)
		{
			if (obj.delete()) //deleting the file
			{
				System.out.println("File Deleted Successfully...");
			}
			else
			{
				System.out.println("File deletion failed...");
			}
		}
		else
		{
			System.out.println("File does Not Exist...");
		}
	}
}

Output

File Deleted Successfully...