codescracker


java

Java Program to Delete Files



« Previous Program Next Program »


Delete Files

To delete files in Java Programming, you have to ask to the user to enter the file name with extension that is to be delete. Now delete that file using the method delete() as shown in the following program.

Java Programming Code to Delete Files

Following Java Program ask to the user to enter the name of the file with extension which is to be delete, then the following program delete that file :

/* Java Program Example - Delete File */
		
import java.io.*;
import java.util.Scanner;

public class JavaProgram
{
   public static void main(String args[]) 
   {
      String fname, str;
      Scanner scan = new Scanner(System.in);
      
      // enter file name with extension to delete
      System.out.print("Enter File Name to Delete : ");
      fname = scan.nextLine();
	  
      try
      {
         BufferedWriter out = new BufferedWriter(new FileWriter(fname));
         out.write("aString1\n");
         out.close();
         boolean success = (new File(fname)).delete();
         if(success)
         {
            System.out.println("The File '" + fname + "' has been Deleted Successfully..!!"); 
           
         }
      }
      catch(IOException e)
      {
            System.out.println("Exception Occurred : " + e);
            System.out.println("File does not exist or deleted..!!");
      }
   }
}

When the above Java Program is compile and executed, it will produce the following output:

Java Program to delete files

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test