How to Delete a File In Java Programming

0 Flares 0 Flares ×

In this tutorial you are gong to learn how to delete a file using Java program, that is we are going to write a Java program that will delete a file from the disk.

Description

To Delete a File in Java we use the File.delete() method of the Java I/O package. This method will delete the file from the physical location on the disk and will return the boolean value ‘true‘ if the operation is successful and will return ‘false‘ if the file is not deleted or the operation fails.

Parameters

No parameters supplied.

Return Value

boolean: ‘true’ or ‘false’

  • true: When the file is successfully deleted
  • false: When the file is not present, or the operation is not successful.

Exceptions

N/A

So below is the example code in Java to delete a file.

package com.lessonslab.io.file;

import java.io.File;

public class DeleteAFileInJava
{
public static void main(String[] args)
{
// Initialize the location of the file
String fileLoc = "c:\\mytestfile.txt";
// Create a new File Object
File myFile = new File(fileLoc);
// Physically the file is deleted and simultaneously we are checking the
// returned result from the method delete()
if (myFile.delete())
{
System.out.println("My New File Deleted");
}
else
{
System.out.println("File does Not exist.");
}
}
}

The above program will output My New File Deleted if the deletion is successful else it will output File does Not Exist.

Guru

+Ayodhyanath Guru holds a B.Tech degree in Electrical Engineering and has worked with various prestigious clients in the IT industry and presently working as a Software Engineer. He is a part time blogger and presently authors the Jafaloo.Com blog. Being a tech enthusiast Guru likes to surf the web and blogs about interesting technical topics like How-To guides, freewares, Tutorials, Software, Gadgets, web applications etc. Apart from blogging he likes coding in Java/J2EE and PHP.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 0 Flares ×