Java目录搜索 - 强制转换,只能搜索1个字符串

时间:2017-01-26 16:31:55

标签: java filewriter directorysearcher

File fe = new File("C:\\Users\\" + System.getProperty("user.name") + "\\desktop" + "\\SearchResults.txt");
    String customLoca = "C:\\Users\\" + System.getProperty("user.name") + "\\AppData" + "\\roaming" + "\\.minecraft" + "\\mods" + "\\1.7.10";

    FileWriter fw = null;
    try {
        fw = new FileWriter(fe);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    File dir = new File(customLoca);
    for (File f : dir.listFiles()) {
        if (f.getName().contains("Toggle")){ 
            try {
                fw.write("Found: "   + f.getName());
                fw.write("\r\n===");
                fw.write("\r\n"); 

            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    }
    try {
        fw.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}
}

基本上上面的代码会创建一个包含结果的文本文档。但是我必须使用我希望它找到的文件进行大小写。例如,如果我用“toggle”替换“Toggle”,则不会出现任何内容。有没有办法让这个Case-Insensitive?另外,有没有办法可以添加else参数。因此,如果没有找到任何内容,它将在文本文档中打印“Nothing Found”。感谢。

2 个答案:

答案 0 :(得分:0)

您可以在支票中尝试!string.equalsIgnoreCase() - 尝试应用以下内容:

if (!toggle.equalsIgnoreCase(file.getName()))

修改

你也可以尝试重构这段代码:

        StringBuilder paragraph = new StringBuilder();
        paragraph.append("I am at office.")
                .append("I work at oFFicE.")
                .append("My OFFICE");
        String searchWord = "office";
        Pattern pattern = Pattern.compile(searchWord, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(paragraph);
        int count = 0;
        while (matcher.find())
            count++;
        System.out.println(count);

答案 1 :(得分:0)

不能使用equalsIgnoreCase(),因为它需要匹配整个名称。 建议:

  • 使用正则表达式匹配您的名字

  • 使用try with resources

  • 尝试可以跨越整个方法,多次尝试较慢

  • 将StringBuilder用于cat string(不像过去那样重要)

  • Java不要求\ r - \ n将编写适当的操作系统新行

  • 永远不会捕获异常,这是一个过度概括

  • 您可以使用String" reset"而不是其他,但其他方面也有效。

     File fe = new File("C:\\Users\\" + System.getProperty("user.name") + "\\desktop" +
                               "\\SearchResults.txt");
     String customLoca =
            "C:\\Users\\" + System.getProperty("user.name") + "\\AppData" + "\\roaming" +
                    "\\.minecraft" + "\\mods" + "\\1.7.10";
    
    try (FileWriter fw = new FileWriter(fe))
    {
       File dir = new File(customLoca);
         for (File f : dir.listFiles())
         {
           String contents = "Nothing Found";
           if (f.getName().matches("(?i).*toggle.*")));
           {
               contents = new StringBuilder("Found: ")
                           .append(f.getName())
                           .append("\n===\n").toString();
           }
           fw.write(contents);
        }
    } 
    catch (IOException ioe)
    {
        ioe.printStackTrace();
    }