I’m having a problem, I’m using a text file that has over a million lines of numbers. the data is in the format below, some lines have 3 pieces of data while others have only 2.
Each time the file gets to the data with only 2 bits, it seems to throw a null error (I’m using Try/catch to read the input stream)
If I remove the value 3 tokenizer then the program runs to the end.
Do I need to put an if statement to check if there is another token after the 2nd line? if so – how??
while ((getLine = br.readLine()) != null) {
StringTokenizer tokenizer = new StringTokenizer(getLine);
String Value1 = tokenizer.nextToken();
String Value2 = tokenizer.nextToken();
String Value3 = tokenizer.nextToken();
//Does some more things
}
The data
11 22 33
44 55
77 88 99
10 11
13 14
16 17 18
You will have to check that there are still tokens in the tokenizer. You can do it like this:
Which will set
Value3tonullif there is no 3rd token. You might want to instead set it to the empty string.The alternative is to use
getLine.split("\\s+"), which will return an array of tokens. If there are only 2 values, the array will be of length 2. So be careful when attempting to read the 3rd value, which might not be present.