How to use a FilenameFilter to filter all content in directory in java?

FilenameFilter class use just names of the files to filter them

First Example: FilenameFilter to retrieve only txt files:

package com.nourit.javaIO;

import java.io.File;
import java.io.FilenameFilter;

public class FilenameFilter1 {

  public static void main(String[] args) {
    File folder = new File("D:/tmp");
    // FilenameFilter to retrieve only txt files
    FilenameFilter txtFileFilter = new FilenameFilter() {
      @Override
      public boolean accept(File dir, String name) {
        if (name.endsWith(".txt")) {
          return true;
        } else {
          return false;
        }
      }
    };

    // files
    File[] files = folder.listFiles(txtFileFilter);
    for (File file : files) {
      System.out.println(file.getName());
    }
  }
}

Output:

nourit-test-1.txt
nourit-test-2.txt
nourit-test-3.txt
nourit.txt
nourit1.txt

Second Example: If you want to filter the files using properties like size of the file, use FileFilter.

FileFilter to retrieve the files smaller than 5MB.

package com.nourit.javaIO;

import java.io.File;
import java.io.FileFilter;

public class FilenameFilter2 {

  public static void main(String[] args) {
    File folder = new File("D:/tmp");
    //FileFilter to retrieve the files smaller than 5MB
    FileFilter sizeFilter = new FileFilter() {
      @Override
      public boolean accept(File file) {
        if (file.length() < 5 * 1024 * 1024) {
          return true;
        } else {
          return false;
        }
      }
    };
    File[] files = folder.listFiles(sizeFilter);
    for (File file : files) {
      System.out.println(file.getName());
    }
  }
}

 

 

 

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.

*