Low Orbit Flux Logo 2 F

Java How To Delete A File

Deleting a file in Java is easy. Here is an example showing how it can be done.

import java.io.File; 

public class Test1 {
    public static void main(String[] args) { 
        File file1 = new File("test_data1.txt"); 
        if (file1.delete()) { 
            System.out.println("File deleted: " + file1.getName());
        } else {
            System.out.println("Error - Can't delete file.");
        } 
    } 
}

In the above example we specified a relative path for a single file: “test_data1.txt”. We can also specify an absolute path. The path can refer to either a file or a directory. If it does refer to a directory then that directory must be empty.

Video