Implementing the Search Functionality


The FileList.java file implements the core functionality of the File Search application. This file reads the location and text pattern that the end user specifies on the File Search Utility window and retrieves information, such as the number of files meeting the search criteria, file names , start position of the specified text pattern within these files, and file sizes. Finally, the FileList.java file passes this information to the Search.java file, which displays this search information to the end user in a tabular format.

Listing 4-2 shows the contents of the FileList.java file:

Listing 4-2: The FileList.java File
start example
 /* Imports the required I/O classes. */ import java.io.FileInputStream; import java.io.File; import java.io.IOException; /* Imports the required NIO classes. */ import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.channels.FileChannel; import java.nio.charset.UnsupportedCharsetException; /* Imports the required Util classes. */ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.Vector; /* Imports the required Swing classes */ import javax.swing.JOptionPane; /* class FileList - This class is the subclass of the application. It displays the list of files in a tabular format. */ public class FileList {    /* Initialize the object of Search class. */    Search se;    int option;    int count = 1;    /*    Declare the default constructor of the FileList class.    */    public FileList(Search se)    {       this.se = se;    }    /*    listFiles() - This method is called when the end user clicks the Search button of the application.    Parameter:     dirname: It is a string type that contains the name of the directory.    Return Value - NA    */    public void listFiles(String dirname)    {       String encodingName = "UTF-8";       /* Set the flag value to CASE INSENSITIVE. */       int flags = Pattern.CASE_INSENSITIVE;        try       {                   /*          Initialize the instance of the Charset class and register the class with the           encoding name.          */          Charset charset = Charset.forName(encodingName);          /*          Initialize the pattern object and compile it with the search pattern specified           by the end user.          */                Pattern pattern = Pattern.compile(se.strText, flags);          try          {              /*             Create a file object that contains the names of all the files and directories.             */             File folder = new File(dirname);             /*             Store the list of files and directories in a String array.             */             String files[] = folder.list();             for (int i=0; i<files.length-1; i++)             {                File file = new File(folder.getAbsolutePath() + File.separator + files[i]);                /*                Check if the file object is a file or a directory.                */                if (se.FLAG == 0)                {                   if (file.isFile())                   {                      /* This will store the complete text of the file. */                      CharBuffer chars;                      try                      {                         /*                         Handle the errors of each file locally and open a file channel to the named file.                         */                         FileInputStream stream = new FileInputStream(file);                         FileChannel f = stream.getChannel();                         /*                         Calls the map() method of the FileChannel class, which returns an                          object of the ByteBuffer class. The map() method uses the                         MapMode.READ_ONLY attribute of the FileChannel class to open the files.                         */                         ByteBuffer bytes = f.map(FileChannel.MapMode.READ_ONLY, 0, f.size( ));                         /*                         We can close the file once it is mapped to the memory.                          Closing the stream closes the file channel also.                         */                         stream.close( );                         /*                         Decode the entire ByteBuffer into one big CharBuffer.                         */                         chars = charset.decode(bytes);                      }                      catch(IOException e)                       {                          /*                         File not found. Print an error message. Move to the next file.                         */                         System.err.println(e);                          continue;                      }                      /*                      A Matcher holds the state of a given pattern and text. Start matching the text.                      */                      Matcher matcher = pattern.matcher(chars);                      while(matcher.find())                       {                          try                         {                            se.vRow = new Vector();                            /*                            Add elements to the row vector.                            */                            se.vRow.addElement(file.getName());                            se.vRow.addElement(Integer.toString(matcher.start()));                            se.vRow.addElement(file.getParent());                            se.vRow.addElement(Long.toString(file.length()) + " bytes");                            /*                            Add a row to the table model.                            */                            se.model.addRow(se.vRow);                             se.countFile = 1;                            se.labelResult.setText(Integer.toString(se.model.getRowCount()) + "file(s) found");                   }                   catch(Exception e)                   {                      System.out.println("Error!" + e);                   }                }                }                else                /*                If the file object is a directory, it calls the listFiles() method again.                */                listFiles(file.getAbsolutePath());             }             else if (se.FLAG == 1)             {                break;                                  }          }       }       catch (Exception ex)       {          /*  Print Error message. Return. */          ex.printStackTrace();          return;          }       }       catch(UnsupportedCharsetException e)        {          /*          Bad encoding name. Print exception name.          */          System.err.println("Unknown encoding: " + encodingName);       }       catch(PatternSyntaxException e)        {           /*          Bad pattern-matching. Print exception name.          */          System.err.println("Syntax error in search pattern: " + e.getMessage());       }       if(se.countFile == 0)       {          JOptionPane.showMessageDialog(null, "No file found!", "Alert Message",          JOptionPane.WARNING_MESSAGE);          se.countFile = 1;       }          } } 
end example
 

Download this Listing .

The above listing creates an instance of the FileList class, which accepts the Search class as an input parameter. When an end user clicks the Search button on the File Search Utility window, the listFiles() method is invoked. The dirname parameter of this method stores the file location specified by the end user. The listFiles() method creates a new instance of the Charset class and registers it with Unicode Transformation Format-8 (UTF-8). Next, the method creates an instance of the Pattern class, initializes the pattern object, and stores the text pattern specified by the end user in this pattern object. The listFiles() method creates a file object using the directory location specified by the end user. Next, the listFiles() method calls the list() method of the File class to retrieve a list of files and subdirectories available within the specified directory location and stores this list in the files[ ] String array.

The listFiles() method now iterates through the files[ ] String array to check for the type of files. If the file is of the type File class, the listFiles() method creates a new instance of the FileInputStream class and calls the getChannel() method of this class. The getChannel() method returns an object of the FileChannel class. Next, the listFiles() method calls the map() method of the FileChannel class, which returns an object of the ByteBuffer class. The listFiles() method then calls the close() method of the FileInputStream class to close the file after it is mapped to the memory.

After mapping the files available at the specified location and containing the specified text pattern to the memory, the listFiles() method calls the matcher() method of the Pattern class. The Pattern class contains the text pattern specified by the end user. The matcher() method returns an object of the Matcher class. The listFiles() method calls the find() method of the Matcher class to obtain information about the files that contain the specified text pattern. The search result, which contains the total number of files along with file information, such as file name and file size, is then returned to the Search class to be displayed to the end user.




Java InstantCode. Developing Applications Using Java NIO
Java InstantCode. Developing Applications Using Java NIO
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 55

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net