Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Delete a File in Java

Using java.io.File package, you can delete a file. See the example below. 

 

package com.seleniummaster.examplefile;

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

public class DeleteFile {

    public static void main(String[] args)
    {
        DeleteAFile("test1.txt");
    }

//Delete a file
    public static void DeleteAFile(String filename) {
        //get current project path
        String filePath = System.getProperty("user.dir");
        //create a new file
        File file = new File(filePath + "\\" + filename);
        try {
            if (!file.exists()) {
                file.createNewFile();
                System.out.println("File is created");
            } else {
                //delete a file
                System.out.println("File already exist");
                file.delete();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    }

Run the code and see the result below. The file has been deleted

File already exist

Process finished with exit code 0