Wednesday, June 25, 2014

File search Program [Java][Search Based on File Name + Text Content]

This program only finds matching file names && (word) content and displays the results to the user. It does NOT search in any sub-directories (to keep it simple). I'll be posting the complete code (with sub-directory search) soon. [Here's the link : post]

import java.util.regex.*;
import java.io.*;
import java.util.*;

public class DirList {
 public static void main(String[] args){
  if(args.length<2){
   System.out.println("Usage: java DirList <directory path> <file names to match (regex)> <word1 to look for in files> <another word> <and so on>");
   return;
  }
  File path = new File(args[0]);
  String[] list; 
  list = path.list(new DirFilter(args));
  Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
  for(String dirItem : list)
   System.out.println(dirItem);
 }
}

class DirFilter implements FilenameFilter{
 private Pattern pattern;
 private  String[] clWords;

 public DirFilter(String[] args){
  pattern = Pattern.compile(args[1]);
  clWords = new String[args.length-2];
  for(int i=2;i<args.length;i++) clWords[i-2] = args[i];
 }

  /*
    The list() method above tests the "name" of each file 
    in the directory "dir" to match the regex and to check whether 
    the file contains ANY (check the Collections.disjoint() function) 
    words specified by the user
  */
 public boolean accept(File dir, String name){ 
  if(pattern.matcher(name).matches()){ 
   if((new File(dir.getAbsolutePath()+"\\"+name)).isFile()){ 
    TextFile tf = new TextFile(dir.getAbsolutePath()+"\\"+name,"\\W+");
    if(Collections.disjoint(tf, Arrays.asList(clWords)))
     return false;
   }
   return true;
  }
  return false;
 }
}

//Helper (File Reader) class - Reads the words of the specified file into an ArrayList<String>

class TextFile extends ArrayList<String> {
  // Read a file as a single string:
  public static String read(String fileName) {
    StringBuilder sb = new StringBuilder();
    try {
      BufferedReader in= new BufferedReader(new FileReader(
        new File(fileName).getAbsoluteFile()));
      try {
        String s;
        while((s = in.readLine()) != null) {
          sb.append(s);
          sb.append("\n");
        }
      } finally {
        in.close();
      }
    } catch(IOException e) {
      throw new RuntimeException(e);
    }
    return sb.toString();
  }

  // Read a file, split by any regular expression:
  public TextFile(String fileName, String splitter) {
    super(Arrays.asList(read(fileName).split(splitter)));
    // Regular expression split() often leaves an empty
    // String at the first position:
    if(get(0).equals("")) remove(0);
  }
  // Normally read by lines:
  public TextFile(String fileName) {
    this(fileName, "\n");
  }
}

No comments:

Post a Comment