tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > IO > File Filter

File Filter 

The following example shows how to filter the contents of a given directory using FileFilter. Here we filter out the text files from the given directory.

File Name  :  
com/bethecoder/tutorials/io/FileFilterTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.io;

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

public class FileFilterTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    File directory = new File("C:\\NEW");
    File [] filesInDir = directory.listFiles(new TextFileFilter());
    
    System.out.println("Directory file listing of " + directory);
    for (int i = ; i < filesInDir.length ; i ++) {
      System.out.println(filesInDir[i]);
    }
  }

}

class TextFileFilter implements FileFilter {

  @Override
  public boolean accept(File file) {
    
    if (file.getName().toLowerCase().endsWith(".txt")) {
      return true;
    }
    
    return false;
  }
}
   

It gives the following output,
Directory file listing of C:\NEW
C:\NEW\file_ops.txt
C:\NEW\Oracle Identity Manager.txt
C:\NEW\readonly_file.txt
C:\NEW\test.txt



 
  


  
bl  br