In this post we will see an example on how we can delete file in java. We will see examples of the File.delete() and File.deleteOnExit() methods in detail
Example : Delete File in java using File.delete()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.kscodes.sampleproject; import java.io.File; import java.io.IOException; public class FileHandling { /** * @param args */ public static void main(String[] args) throws IOException { deleteFile(); } public static void deleteFile() throws IOException { File file = new File("C:\\testFile.txt"); boolean fileDeleted = file.delete(); if (fileDeleted) { System.out.println("File Deleted successfully"); } else { System.out.println("File couldnt be Deleted"); } } } |
File.delete() returns “true” if a file is deleted from the given path.
It returns “false” if no file is found or if it is unable to delete the file.
You can also delete file in java using
File.deleteOnExit() method.
You can get more details about this method here