Home Regularexpressions Listing Directory using Regular expression
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Listing Directory using Regular expression

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

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
Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 26, 2008

Ask Questions?    Discuss: Listing Directory using Regular expression  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com