Home Java Example Java Io Delete a File



Delete a File
Posted on: February 27, 2008 at 12:00 AM
In this section, you will learn how a specified file or directory is deleted. For deleting a file from a directory you need to give the file name to be deleted.

Delete a File 

     

In this section, you will learn how a specified file or directory is deleted. For deleting a file from a directory you need to give the file name to be deleted.

Description of program:

The following code of program deletes a file from a directory. In this program the compiler will ask to enter the name of the file to be deleted. For this we have used "BufferedReader(new InputStreamReader(System.in));" method as you very well know about it. If the file exists in the directory then it will be deleted otherwise we will get a message that "file was not successfully deleted".

import java.io.File;
import java.io.*;

public class DeletingFile {
  public static void main(String args[])throws IOException{
  BufferedReader in = new BufferedReader(new 
  InputStreamReader
(System.in));
  System.out.print("Enter the file name to delete:");
  String file_name = in.readLine();
  File file = new File("File already exist!");
  boolean exist = file.createNewFile();
 if (!exist){
 System.out.println("File was successfully deleted.\n");
 else {
 System.out.println("File was not successfully deleted.\n");
 }
 }
}
  

Output of the program:

C:\unique>javac DeletingFile.java

C:\unique>java DeletingFile
Enter the file name to delete:wonderful.txt
File was successfully deleted.

C:\unique>

Download this example.

Related Tags for Delete a File:
ccomfilecompilerscriptdeleteinputdirectoryiomethodsedgetstreamsystemcompileipbuffernewreadnamepilthismessageinputstreamifforiestreamreaderexistsprogramwasmpitolearnramcidescriptioneareilreadersuccessitdessectionnotputusewiseulpefromceenterinnodeletingasmntouttrsageletadesspecstsemdirfullbufferedreaderagepiinputsmehowprosystorsrectsussaspdelctoreedirectessbufferedatkisirhallivfolloweaarcodcodeccstrsatstreamwingwisufxiscrssriripsystem.inthavstabhatexictofeprodeonomogrolonp


More Tutorials from this section

Ask Questions?    Discuss: Delete a File   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.