CodeTalk
CodeTalk

Reputation: 3657

Search Recursively for a value provided within a set directory

I'm trying to find a string within the directory C:\ which is currently hardcoded. Within this C:\ directory, I'm looking to recursively find the inputted string (inputString) within the root/and subdirectories and finally output the names of the files containing those strings.

I hope the above clarifies my initial question

I currently have assess.java:

import javax.swing.JFrame;

/* Notes: Event - user clicking button, moving mouse
 *  EventHandler - code that response to users action
 * 
 */

class assess {
    public static void main(String args[]){

        assesshelper assessment1 = new assesshelper();
        assessment1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        assessment1.setSize(500,500); // set size of window
        assessment1.setVisible(true);
    }
}

and assesshelper.java

import java.awt.FlowLayout; // orientation of screen
import javax.swing.JFrame; // JFrame all basic windows features (min/maximize), title
import javax.swing.JTextField; // Typing text
import javax.swing.JLabel; // output text / images


public class assesshelper extends JFrame {

    private JLabel item1;

    private JTextField theUrl;

    public assesshelper(){ // anything within assesshelper is within window
        super("Assess"); // title of window
        setLayout(new FlowLayout()); // gives us default label

        //item1
        item1 = new JLabel("Welcome!");
        add(item1); // add item1 to the screen


        String setDir = "C:/";
        JTextField inputString = new JTextField();

        inputString.setText("ENTER DIR TO PROCESS");
        /// BEGIN SEARCHING FOR INPUTTED STRING HERE WITHIN ROOT/SUBDIRECTORIES, OUTPUT FILE NAMES CONTAINING STRING

        add(inputString);

    }

}

How do I recursively search for the value of inputString within the directory set by setDir?

(Java-newbie here -- please keep it constructive)

Upvotes: 0

Views: 224

Answers (2)

LanguagesNamedAfterCofee
LanguagesNamedAfterCofee

Reputation: 5952

Considering you are new, this is a simple recursive solution (in no means the most efficient though):

public static final FileFilter DIRS = new FileFilter() {

  public boolean accept(File file) {
    return file.isDirectory();
  }

};

public static final FileFilter FILES = new FileFilter() {

  public boolean accept(File file) {
    return file.isFile();
  }

}

public void walkTree(File start) throws IOException {

  File[] dirs = start.listFiles(DIRS);
  File[] files = start.listFiles(FILES);

  for (File file : files) {
    if (file.canRead()) {
      if (readAndCheck(file, "string")) {
        // Do Whatever
      }
    }
  }

  for (File dir : dirs) {
    walkTree(dir);
  }

}

public boolean readAndCheck(File file, String string) throws IOException {

  BufferedReader br = null;
  StringBuilder total = new StringBuilder();

  try {

    // If line separators matter in your pattern, consider reading every character
    br = new BufferedReader(new FileReader(file));
    String line;
    while ((line = br.readLine()) != null) {
      total.append(line);
    }

  } finally {
    if (br != null) {
      br.close();
    }
  }

  return total.toString().contains(string);

}

Note: There may be a couple syntax errors as I wrote this in the answerbox.


Also, you're going to have to launch this on a new Thread, preferably using a SwingWorker:

Upvotes: 2

MadProgrammer
MadProgrammer

Reputation: 347204

Taking LanguagesNamedAfterCofee answer into account, you can read files relatively easily...

public void searchFile(File file, String value) throws IOException {

    FileReader fr = null;
    BufferedReader br = null;
    try {

        fr = new FileReader(file);
        br = new BufferedReader(fr);

        int line = 1;
        String text = null;
        while ((text = br.readLine()) != null) {
            if (text.toLowerCase().contains(value.toLowerCase())) {
                System.out.println("found " + text + " in " + file + " @ [" + line + ":" + text.toLowerCase().indexOf(value.toLowerCase()) + "]");
            }
            line++;
        }
    } finally {
        try {
            fr.close();
        } catch (Exception e) {
        }
        try {
            br.close();
        } catch (Exception e) {
        }
    }
}

Now this example will only read text files (it will read binary files, but the usefulness is negotiable) and print out the file and line where the value was found.

Ideally, you could pass this information back to the client via some kind of callback method, model or collect the information for later use...

Upvotes: 0

Related Questions