在文件中搜索字符串

Searching a String in a file

我想在 Java 中编写一个函数来搜索文本文件中的特定字符串。我应该使用哪个循环以及如何使用? (说是while循环,条件是什么?)

我通常使用的是 BufferedReader 并创建一个 while 循环,如

while((line = reader.readLine()) != NULL) {
    //do stuff
}

最常用的循环是 while 循环,因为您需要循环并比较从文件中退出的字符串是否不是 null。 好了,说到这里,让我们看一些代码。您可以编写的解决方案是首先在 BufferedReader 实例中打开文件,然后逐行读取文件并查看该行是否包含您要查找的字符串。 如果是这样,您可以使用 boolean 变量并将其分配给 true,否则将其分配给 false。 你可以在 Java 中有这样的东西:

public static boolean findStringFile(String lookingForMe, String pathFile)
{

    boolean found = false;
    try{
        BufferedReader br = new BufferedReader(new FileReader(pathFile));
        try{
            String line;
            while ((line = br.readLine()) != null)
            {
                if (line.contains(lookingForMe))
                    found = true;
            }
        } finally {
            br.close();
        }
    } catch(IOException ioe)
    {
        System.out.println("Error while opening the file !");
    }
    return found;
}

此函数将获取 String lookingForMe 作为第一个参数,代表您在文件中搜索的字符串,作为第二个参数 String pathFile,代表文件的路径(它可以只是 nameOfTheFile.extension 当它在项目的根目录中时)。

希望对您有所帮助。

编辑

如果您的文件有问题(文件不存在或由于特权或其他原因无法打开)或任何其他问题,则以下代码部分(下方)的执行并不总是成功, 执行将停止并抛出异常。

BufferedReader br = new BufferedReader(new FileReader(pathFile));

            String line;
            while ((line = br.readLine()) != null)
            {
                if (line.contains(lookingForMe))
                    found = true;
            }

"try" 的目标是通过显示用户错误消息(您用 system.out.println("Your error message") 指定的错误消息)来避免此类问题。

您应该使用的适当代码(以避免上面列出的问题)是带有 try 块的代码(第一个)。

有关 Java 中异常的进一步解释,我建议访问此链接:https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html