0

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

        }

    }
Kishore kumar
  • 81
  • 1
  • 6

3 Answers3

1

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

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.

dly
  • 1,080
  • 1
  • 17
  • 23
0

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.

Community
  • 1
  • 1
akhil_mittal
  • 23,309
  • 7
  • 96
  • 95