Home > Tutorial > Java Delete File Sample Code

Java Delete File Sample Code

This sample Java code will attempt to delete a file from the file system. The File delete() method will return a boolean that is true if the file was able to be deleted or false if the file was not able to be deleted. Unsuccessful deletion may be due to file not present or improper file permissions.

It’s also worth noting that the delete() method can also delete a directory or folder. The folder or directory must be empty in order for it to be deleted.

Java Class: File
Method Name: delete()
Parameters: none
Return Type: boolean
Exceptions: SecurityException

Java File Delete Source Code:

package com.jcd.java.tutorials;

import java.io.File;

public class JavaDeleteFile 
{

	public static void main(String[] args) 
	{
		
		String sampleJavaFile = "C:\\Users\\Admin\\Documents\\JavaFileTest1.txt";
		
		try 
		{
			//Create a File object
			File file = new File(sampleJavaFile);
			
			//Delete the file or directory
			if(file.delete())
			{
				System.out.println(file.getName()+" Has Been Deleted!");
			}
			else 
			{
				System.out.println("Problem Deleting File or Directory: "+file.getName());
			}
		
		}
		catch(Exception ex)
		{
			System.out.println("Exception:"+ex.toString());
		}
	}

}


Here is the sample output if the file or directory exists and was successfully deleted from the file system.

Java File Delete Output:

JavaFileTest1.txt Has Been Deleted!


Here is the sample output if the file or directory was NOT able to be deleted from the file system.

Java File Delete Output:

Problem Deleting File or Directory: JavaFileTest1.txt


The Java File class also has a related method called deleteOnExit(). If an application calls this method to delete a file or directory, it will attempt to delete file or directory just before exiting the virtual machine. Use this method with caution because once a deletion has been requested, it is not possible to cancel the request.

In terms of a practical application, I suppose this method would be useful when an application uses temporary files that it would like cleaned up upon exiting.



References:

Seymour
Posted by

Seymour

I have been a software developer for twenty years now focusing on writing high quality Java applications. If you are in a programming field, you know that technology is constantly changing. You have to keep current or you will get left behind!

You may also like...

Leave a Reply

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

Copyright © 2018 JavaCodeDepot