1

I was wondering, If i had a java class, that wanted to consult a txt file with say a list of names like

tom
steve
jones

how could i open the text file in the java program and basically see if a string contained in the program matches one of these names?

so far i have come up with

                try {
                BufferedReader inputReader = new BufferedReader(new FileReader("users.txt"));

                while (inputReader.readLine() != null){

                }

            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException ep) {
                // TODO Auto-generated catch block
                p.printStackTrace();
            }

but do not no where to go from here..

danben
  • 80,905
  • 18
  • 123
  • 145
KP65
  • 13,315
  • 13
  • 45
  • 46

1 Answers1

3

You need to store the result of readLine(), like:

String nextLine;
while ((nextLine = inputReader.readLine()) != null){
if (nextLine.equals(stringToCheck)) {
    //do something
  }
}

(where stringToCheck is the target string, of course.)

danben
  • 80,905
  • 18
  • 123
  • 145
  • 1
    +1. my two cents: equals, equalsIgnoreCase, contains or even regular expressions via Pattern.compile are your friends for string-matching – Karussell Feb 24 '10 at 19:46
  • 1
    Maybe it contained whitespace. Just call `trim()` before `equals()`. I.e. `if (nextLine.trim().equals(stringToCheck)) {}` – BalusC Feb 24 '10 at 20:30