简体   繁体   中英

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 =)

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.

Use Scanner.nextLine() to get the entire line in one go.

scanner.nextLine() would solve your problem. 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.

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 . Also check this link for fast way of searching a string in file. Also keep in mind to close scanner once you are done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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