在文件中查找单词-如果文件包含将输出到控制台的路径[关闭]

问题描述 投票:-1回答:1

我需要创建一个程序,它执行一些操作:

  • 采用参数:要查找的单词和要查找的路径
  • 在文件中逐个查找给定的单词
  • 如果在文件中找到单词->打印到控制台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)

也许是解决此问题的另一种方法?

java file search
1个回答
3
投票

您在这里犯了几个错误。。

[...]
  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()**));
   [...]
© www.soinside.com 2019 - 2024. All rights reserved.