Tuesday 20 January 2015

Java-Delete files for the file names starting with "Test-"

Java Program to delete files for the file names starting with "Test-"

package fileio;
import java.io.File;
import java.io.FilenameFilter;

public class DeleteFileName {

    public static void main(String[] args) {
        try {

            final String filePrefix = "Test-";
            String filesDir = System.getProperty("user.dir") + "\\src\\fileio";

            File dir = new File(filesDir);
            File[] foundFiles = dir.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.startsWith(filePrefix);
                }
            });

            System.out.println("Number of files found : " + foundFiles.length);
            System.out.println("");
            for (File file : foundFiles) {

                try {
                    if (file.delete()) {
                        System.out.println(file.getName() + " is deleted!");
                    } else {
                        System.out.println("Delete operation is failed, unable to delete the file.");
                    }

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

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


Executing the above java program:

Output:



No comments:

Post a Comment