In Java, we can use the NIO Files.delete(Path) and Files.deleteIfExists(Path) to delete a file.

1. Delete a file with Java NIO

1.1 The Files.delete(Path) deletes a file, returns nothing, or throws an exception if it fails.

DeleteFile1.java

package com.favtuts.io.file;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class DeleteFile {

    public static void main(String[] args) {
        
        String fileName = "/home/tvt/workspace/favtuts/test.txt";
        try {
            Files.delete(Paths.get(fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
}

If the file doesn’t exist, it throws NoSuchFileException.

java.nio.file.NoSuchFileException: /home/tvt/workspace/favtuts/test.txt

1.2 The Files.deleteIfExists(Path) also delete a file, but it returns a boolean, true if file deletion success; false if the file doesn’t exist, no exception is thrown.

DeleteFile2.java

package com.favtuts.io.file;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class DeleteFile {

    public static void main(String[] args) {
        
        String fileName = "/home/tvt/workspace/favtuts/test.txt";       
        deleteFileNoException(fileName);
    }
    
    private static void deleteFileNoException(String fileName) {
        try {
            boolean result = Files.deleteIfExists(Paths.get(fileName));
            if (result) {
                System.out.println("File is deleted!");
            } else {
                System.out.println("Sorry, unable to delete the file.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output If the file doesn’t exist

Sorry, unable to delete the file.

2. Delete a file with Java IO

2.1 For the legacy File IO java.io.*, we can use the File.delete() to delete a file, and it will return boolean, true if file deletion success, false otherwise.

DeleteFile3.java

    private static void deleteFileLegacyIO (String fileName) {
        try {
            File file = new File(fileName);
            if (file.delete()) {
                System.out.println(file.getName() + " is deleted!");
            } else {
                System.out.println("Sorry, unable to delete the file.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2.2 The File.deleteOnExit() is a bit special, it will delete the file when the JVM terminates normally. However, there is no guarantee on the file deletion, use it with care, or avoid this method.

  File file = new File(fileName);
  file.deleteOnExit();

Note

The legacy File IO java.io.* had several drawbacks, always picks Java File NIO, java.nio.*.

3. Delete files with certain extension only

In Java, you can implements the FilenameFilter, override the accept(File dir, String name) method, to perform the file filtering function.

In this example, we show you how to use FilenameFilter to list out all files that are end with “.txt” extension in folder “c:\\folder“, and then delete it.

DeleteFile4.java

package com.favtuts.io.file;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class DeleteFile {

    private static final String FILE_DIR = "/home/tvt/workspace/favtuts/folder";
    private static final String FILE_TEXT_EXT = ".txt";

    public static void main(String[] args) {     
        new DeleteFile().deleteFile(FILE_DIR, FILE_TEXT_EXT);
    }    
    
    public void deleteFile(String folder, String ext) {

        GenericExtFilter filter = new GenericExtFilter(ext);
        File dir = new File(folder);

        // list out all the file name with .txt extension
        String[] list = dir.list(filter);
        if (list.length == 0) return;
        
        File fileDelete;
        for(String file : list) {
            String temp = new StringBuffer(FILE_DIR)
                .append(File.separator)
                .append(file).toString();
            fileDelete = new File(temp);
            boolean isdeleted = fileDelete.delete();
            System.out.println("file : " + temp + " is deleted : " + isdeleted);
        }
    }


    // inner class, generic extension filter
    public class GenericExtFilter implements FilenameFilter {

        private String ext;

        public GenericExtFilter(String ext) {
            this.ext = ext;
        }

        public boolean accept(File dir, String name) {
            return (name.endsWith(ext));
        }
    }
}

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-io/file

References

Leave a Reply

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