Java Program to Delete a File

This article is created to cover a program in Java that deletes or removes a file entered by user at run-time of the program.

Delete a File in Java

The question is, write a Java program to delete a file. The name of file must be received by user at run-time. The program given below is its answer. But before the program, here is the snapshot of the current directory, before executing the program given below:

java program delete a file

See the file, codescracker.txt. I'm going to delete this file, with the program given below:

import java.util.Scanner;
import java.io.*;

public class CodesCracker
{
   public static void main(String[] args)
   {
      String filename;
      Scanner scan = new Scanner(System.in);
      
      System.out.print("Enter the Name of File to Delete: ");
      filename = scan.nextLine();
      
      File myfile = new File(filename);
      
      if(myfile.delete())
         System.out.println("\nThe file is deleted successfully!");
      else
         System.out.println("\nSomething went wrong!");
   }
}

The snapshot given below shows the sample run of above program, with user input codescracker.txt as the name of file to delete:

delete a file in Java program

Now if you open the current directory again, then the file codescracker.txt gets deleted. Here is the new snapshot of the directory, after executing the above program:

java delete a file

Important - The file that is going to delete using above program, get deleted for permanent. That is, the deleted file, codescracker.txt, will not be available inside the Recycle Bin. Therefore, be sure to delete garbage or unwanted file. Better to create a new empty file, and delete that file using above program.

Same Program in Other Languages

Java Online Test


« Previous Program Next Program »


Liked this post? Share it!