Check if string exists in text file

Viewed 62

I'm trying to write a method, which checks if a given string exists in a .txt file, but it seems like my if/else statement isn't working correctly.

public void ChcekIfPasswordExsists(String check) throws FileNotFoundException{
    BufferedReader reader = new BufferedReader(new FileReader("Passwords.txt"));
    Scanner fileScanner = new Scanner(reader);
    while(fileScanner.hasNextLine()){
        final String line = fileScanner.next();
        if(line.contains(check)){
            System.out.println("Password for " + check + " already exsits");
            break;
        }
        else{
            System.out.println(check + " is usable");
            break;
        }        
    }
}

This is where I'm calling the method:

System.out.println("Enter the name of the app or website,\nwhere password is going to be use:");
useCase = s.nextLine();
 ChcekIfPasswordExsists(useCase);

I have looked at countless other posts with no effect. No matter what, it seems like the code skips the "if" statement and directly jumps to the "else" statement.

1 Answers

The logic of your while loop should be to iterate over all lines in the file until either you find a match or you hit the end of the file. Consider this version:

public void ChcekIfPasswordExsists(String check) throws FileNotFoundException {
    BufferedReader reader = new BufferedReader(new FileReader("Passwords.txt"));
    Scanner fileScanner = new Scanner(reader);
    boolean flag = false;
    while (fileScanner.hasNextLine()) {
        final String line = fileScanner.next();
        if (line.contains(check)) {
            flag = true;
            break;
        }
    }

    if (flag) {
        System.out.println("Password for " + check + " already exsits");
    }
    else {
        System.out.println(check + " is usable");
    }
}

Also, I might be inclined to change the method signature to return a boolean value (true/false). Based on that return value, you can display to the console the message you want.

Side note: If you are actually storing cleartext passwords in a text file, then stop doing that immediately. It is a security hole. Instead, setup a proper database and only store an irreversible hash of the passwords.

Related