How to delete files with a certain extension from a folder?

Here is an example to expalin how to delete files with a certain extension from a folder.

  • First example:
package com.nourit.javaIO;

import java.io.File;

public class DeleteFilesWithCertainExtension {

  public static void main(String[] args) {
    File folder = new File("D:/tmp");
    String ext = ".tmp";
    File fList[] = folder.listFiles();
    // Searchs .tmp
    for (int i = 0; i < fList.length; i++) {
        String temp = fList[i].getPath();
        if (temp.endsWith(ext)) {
            // and deletes
            boolean isdeleted = (new File(temp).delete());
            System.out.println("file : " + temp + " is deleted : " + isdeleted);
        }
    }
  }
}
  • Second example:
package com.nourit.javaIO;

import java.io.File;

public class DeleteFilesWithCertainExtension1 {

  public static void main(String[] args) {
    File folder = new File("D:/tmp");
    String ext = ".tmp";
    boolean isdeleted = false;
    // Searchs .tmp
    for (File f : folder.listFiles()) {
      if (f.getName().endsWith(ext)) {
        System.out.print("file : " + f.getPath());
        isdeleted = f.delete(); // 
        System.out.println(" is deleted : " + isdeleted);
      }
    }
  }
}
  • Third example Java 8:
package com.nourit.javaIO;

import java.io.File;
import java.util.Arrays;

public class DeleteFilesWithCertainExtension2 {

  public static void main(String[] args) {
    File folder = new File("D:/tmp");
    String ext = ".tmp";
    Arrays.stream(folder.listFiles((f, p) -> p.endsWith(ext))).forEach(File::delete);  
  }

}

Output:

file : D:\tmp\temp-nourit-file-name7880135018657413763.tmp is deleted : true

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*