Listing Directory using Regular expression

This Example describe the way how to list the directory by using Regularexpression.

Listing Directory using Regular expression

--Ads--

Listing Directory using Regular expression

     

This Example describe the way how to list the directory by using Regularexpression.The steps involved in replacing a String are described below:

File directorypath = new File("/home/girish/Desktop/Linux"):-it is the path where my directory is stored.Before running this example create your own directory and give the path of the directory.

String[] list:-Creates an array named list.

list = directorypath.list():-This method returns array of string including the files and directories in the directory followed by this abstract pathname.

list = directorypath.list(new DirFilter(args[0])):-This method returns array of string including the files and directories in the directory followed by this abstract pathname that suits the specified filter.

public boolean accept(File directorypath, String name):-This method is for testing if a specified file should be included in a file list.

pattern = Pattern.compile(regex):-This method compiles the regular expression into a pattern.

 
Listdirectory.java
import java.io.File;
import java.io.FilenameFilter;
import java.util.regex.Pattern;

public class Listdirectory {
  public static void main(String[] args) {
  File directorypath = new File("/home/girish/Desktop/Linux");
  String[] list;
  if (args.length == 0)
  list = directorypath.list();
   else
  list = directorypath.list(new DirFilter(args[0]));
 for (int i = 0; i < list.length; i++)
  System.out.println(list[i]);
  }
}
 class DirFilter implements FilenameFilter {
  private Pattern pattern;

  public DirFilter(String regex) {
  pattern = Pattern.compile(regex);
  }
  public boolean accept(File directorypath, String name) {
 return pattern.matcher(new File(name).getName()).matches();
  }
}

Output of the program:-

linux.doc
new file~
song
new file
Xmlroseindia.odt

Download Source Code