繁体   English   中英

如何在文本文件中搜索字符串备份= True

[英]How to search a String Backup = True in a text file

前后之间有一个空格= ...

(Backup = True)------是要搜索的字符串(=之间有空格)

File file = new File(
                "D:\\Users\\kbaswa\\Desktop\\New folder\\MAINTENANCE-20150708.log.txt");

        Scanner scanner = null;
        try {
            scanner = new Scanner(file);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // now read the file line by line...
        int lineNum = 0;
        while (scanner.hasNextLine()) {
            String line = scanner.next();
            lineNum++;
            String name="Backup = True";
            if (line.contains(name)) {
                System.out.println("I found "+name+ " in file " +file.getName());
                   break;
            }
            else{
                System.out.println("I didnt found it");
            }

        }

    }

Scanner.next()返回下一个完整的令牌,因此它将返回类似Backup ,然后在下一次循环时返回=在下一次返回true

使用Scanner.nextLine()一次性获得整行。

scanner.nextLine()将解决您的问题。 如果您要坚持使用scanner.next() ,则可以定义一个定界符: scanner.useDelimiter("\\n")读取文件,直到到达定界符并从那里开始下一个循环。

您需要逐行读取文件并在每一行中搜索您的字符串。 该代码应类似于:

final Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
   final String lineFromFile = scanner.nextLine();
   if(lineFromFile.contains(inputString)) { 
       // a match!
       System.out.println("Found " +inputString+ " in file ");
       break;
   }
}

现在确定要在Scanner还是BufferedReader之间读取文件,请检查此链接 还要检查此链接以获取在文件中搜索字符串的快速方法。 完成操作后,也请记住要关闭扫描仪。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM