I need to create a program, which does a few things:
- takes parameters: word to find and a path to look
- looking for the given word at files one by one
- If the word has found in the file -> print to console
filename–file path
Traverse all folders with the same parsing algorithm till it will be possible.
Here is code snipped:
class SearchPhrase {
// walk to root way
public void walk(String path, String whatFind) throws IOException {
File root = new File(path);
File[] list = root.listFiles();
for (File titleName : list) {
if (titleName.isDirectory()) {
walk(titleName.getAbsolutePath(), whatFind);
} else {
if (read(titleName.getName()).contains(whatFind)) {
System.out.println("File: " + titleName.getAbsoluteFile());
}
}
}
}
// Read file as one line
public static String read(String fileName) {
StringBuilder strBuider = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new FileReader(new File(fileName).getAbsoluteFile()));
String strInput;
while ((strInput = in.readLine()) != null) {
strBuider.append(strInput);
strBuider.append("\n");
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return strBuider.toString();
}
public static void main(String[] args) {
SearchPhrase example = new SearchPhrase();
try {
example.walk("C:\\Documents and Settings\\User\\Java", "programm");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Program doesn’t compil with following errors:
java.io.FileNotFoundException: C:\Documents and Settings\User\Java Hangman\Java\Anton\org.eclipse.jdt.core.prefs
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
at task.SearchPhrase.read(SearchPhrase.java:28)
at task.SearchPhrase.walk(SearchPhrase.java:16)
at task.SearchPhrase.walk(SearchPhrase.java:14)
at task.SearchPhrase.main(SearchPhrase.java:48)
Maybe is is another approach for solving this issue?
you are doing a couple of mistakes here..
In the above code you are passing the file name to the read method which is wrong. Instead you have to pass the filename along with its path like this…
And there is no need of getAbsoluteFile() here