junior
junior

Reputation: 15

filtered file type search and delete java

This code is at the address I gave me ".txt " lists the name of the files.

I want to delete these files without printing them to the screen. And is it possible to do this in a function, not in two separate classes?

public class file {

    public static void main(String[] args) {
        File f = new File("D:/Users"); 
        String[] allFiles = f.list(new MyFilter ());
        for (String filez:allFiles ) {
            f.delete();
        }
    }
}

class MyFilter implements FilenameFilter {

    @Override
    public boolean accept(final File dir, final String name) {
        return((name.endsWith(".txt")));        
    }
}

Upvotes: 1

Views: 50

Answers (1)

dbz
dbz

Reputation: 421

This code deletes all the files with txt extension inside a folder.

public class file {

   public static void main(String[] args) {

       File folder = new File("D:/Users");

        for (File f : folder.listFiles()) 
        {
             if (f.getName().endsWith(".txt")) 
             {
                f.delete(); 
             }
        }
   }
}}

Upvotes: 1

Related Questions