我需要创建一个程序,它会做一些事情:
- 带参数:要查找的单词和要查找的路径
- 一个一个地在文件中查找给定的单词
- 如果在文件中找到该单词 -> 打印到控制台
filename
-file path
使用相同的解析算法遍历所有文件夹,直到有可能。
这是代码片段:
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();
}
}
}
程序无法编译并出现以下错误:
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)
也许是解决这个问题的另一种方法?