How to search directory for specific files?

How do you search the given word in all files from the directory in java?

  • Answer:

    The program below will search all non-directory files in the starting directory. If you want to search all subdirectories, you'll have to modify it to recurse a bit. Note that this will also only do plain text searches of files. It will most likely not find your string in a MS Word .doc file. Also note that this will not find multiple-line search strings, since it reads and checks one line of the file at a time. { final String dirName; // path of directory you want to search final String str = ""; // string to search for final File dir = new File(dirName); for (File f : dir.listFiles()) { if (!f.isDirectory()) { System.out.println(f + ": " + fileContains(f, str)); } } } // returns true iff f contains str private static final boolean fileContains(final File f, final String str) throws IOException { final BufferedReader in = new BufferedReader(new FileReader(f)); String currentLine; while ((currentLine = in.readLine()) != null) { if (currentLine.contains(str)) { in.close();return true; } } in.close(); return false; }

wiki.answers.com Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.