Delete File Java

Delete File Java

In this sample java class you will see how to delete file. We will use File class method delete() as shown below:

Sample Java class:

package com.javahonk;

import java.io.File;
import java.io.IOException;

public class DeleteFile {

	public static void main(String[] args) {

		try {
			File sourceFile = new File("C:\\JavaHonk\\File\\JavaHonk.txt");

			if (sourceFile.exists()) {

				boolean success = sourceFile.delete();
				if (success) {
					System.out.println("File deleted successfully.");
				}

			} else {

				sourceFile.createNewFile();
				boolean success = sourceFile.delete();
				if (success) {
					System.out.println("File deleted successfully.");
				}

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

	}

}

Output:

Delete File JavaF

For more information about delete file java please read oracle tutorials here

Leave a Reply

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