简体   繁体   English

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

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

There is a space between before and after = ... 前后之间有一个空格= ...

( Backup = True )------ is a String to search(Even space is there between =) (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() returns the next complete token, so it will be returning something like Backup , then = next time round the loop, then true next time. Scanner.next()返回下一个完整的令牌,因此它将返回类似Backup ,然后在下一次循环时返回=在下一次返回true

Use Scanner.nextLine() to get the entire line in one go. 使用Scanner.nextLine()一次性获得整行。

scanner.nextLine() would solve your problem. scanner.nextLine()将解决您的问题。 If you want to stick with scanner.next() you can define a delimiter: scanner.useDelimiter("\\n") this reads the file until it hits the delimiter and starts the next loop from there. 如果您要坚持使用scanner.next() ,则可以定义一个定界符: scanner.useDelimiter("\\n")读取文件,直到到达定界符并从那里开始下一个循环。

You need to read the file line-by-line and search for your string in every line. 您需要逐行读取文件并在每一行中搜索您的字符串。 The code should look something like: 该代码应类似于:

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;
   }
}

Now to decide between Scanner or a BufferedReader to read the file, check this link . 现在确定要在Scanner还是BufferedReader之间读取文件,请检查此链接 Also check this link for fast way of searching a string in file. 还要检查此链接以获取在文件中搜索字符串的快速方法。 Also keep in mind to close scanner once you are done. 完成操作后,也请记住要关闭扫描仪。

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

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