Delete a File in Java

To delete a file in Java, get the file handle to the file that you want to delete. To delete a file in particular directory, Construct File Path to that file, get the file handle to delete the file using the path. Use File.delete() from IO library to delete the file. delete() method will return true, if file is deleted successfully, otherwise, it will return false.

File Delete

package com.jminded.java.io;

import java.io.File;
/**
 * https://jminded.com
 * @author Umashankar
 *
 */
public class DeleteFile {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		try {
			// get the handle to log file
			File fileHandle = new File("c:\\logs\\catalina.out");
			// delete() on file handle will delete the log file
			if (fileHandle.delete()) {
				// successful deletion
				System.out.println(fileHandle.getName() + " is deleted!");
			} else {
				System.out.println("Delete Failed!");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

References

https://docs.oracle.com/javase/8/docs/api/java/io/File.html

Leave a Comment