我需要创建一个程序,它执行一些操作:
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)
也许是解决此问题的另一种方法?
您在这里犯了几个错误。。
[...] if (read(titleName.getName()).contains(whatFind)) { System.out.println("File: " + titleName.getAbsoluteFile()); } [...]
在上面的代码中,您正在将文件名传递给read方法,这是错误的。相反,您必须像这样传递文件名及其路径...
if (read(**titleName.getAbsolutePath()**).contains(whatFind)) { System.out.println("File: " + titleName.getAbsoluteFile()); }
并且这里不需要getAbsoluteFile()
[...]
BufferedReader in = new BufferedReader(new FileReader(new File(
fileName).**getAbsoluteFile()**));
[...]