1

Is it possible (and wise) to check if a value exists in an external text file.

So if i have a file: bankcodes.txt that contains the next lines:

INGB
ABNA
...

Is it possible to check if a value is present in this file?

The reason is that these values can change and need to be easily changed whitout making a new jar file.

If there is another, wiser way of doing this i would like to hear it too.

Mijno
  • 79
  • 1
  • 2
  • 12
  • At start up read in the text file and read all entries line by line into a Set. Then check if your value is present in this set. – zEro Jun 25 '13 at 09:48
  • Possible Duplicate: http://stackoverflow.com/questions/4716503/best-way-to-read-a-text-file – davek Jun 25 '13 at 09:51

2 Answers2

1

From here:

https://stackoverflow.com/a/4716623/110933

Read contents of file line by line and check the value you get for "line" for the value you want:

BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append("\n");
        line = br.readLine();
    }
    String everything = sb.toString();
} finally {
    br.close();
}
Community
  • 1
  • 1
davek
  • 22,499
  • 9
  • 75
  • 95
  • Ok thanks, i had read the other article before creating this question. So this is a decent way to solve such things? – Mijno Jun 25 '13 at 10:02
  • @user: that's the way I'd probably do it. If the file was in, say, CSV format then I'd look at using one of the libraries available such as Open CSVReader. – davek Jun 25 '13 at 10:14
1

Give example how i did it , while File.txt -> our text and ourValue it the one we searching

    String ourValue="value"
    BufferedReader br = new BufferedReader(new FileReader("File.txt"));
    String line = br.readLine();
            boolean exist = false;
            while (line != null&&!exist) {
                if (ourValue.equals(line)) {
                    exist = true;
                } else {
                    line = br.readLine();
                }
            }
    System.out.println("the value " +ourValue+" exist in the Text? "+ exist);
        } 
    
Vladi
  • 1,662
  • 19
  • 30