2

I am using the following code after reading from a text file as to break the input of the text file into tokens:

String input;
while(true)
{
    input = bin.readLine(); 
    if (input == null) 
    {
        System.out.println( "No data found in the file");
        return 0;
    }
    break;
}

StringTokenizer tokenizer = new StringTokenizer(input);

Then:

for (int i=0; i < numAtt; i++) 
{
    attributeN[i]  = tokenizer.nextToken();
}

I cannot understand why the attributeNames gets the tokens in the first line of the text file only, doesn't while(true) keep on reading the whole file? Also is there a way to avoid the while(true) and using break to terminate it?

user90790
  • 305
  • 1
  • 4
  • 13

3 Answers3

1

Your break after if (input == null) { } is breaking the while, so your code only read one line.

Also is there a way to avoid the while(true) and using break to terminate it?

Do it in this way:

while ((input = bin.readLine()) != null) {
    //split input line here 
}

Also, consider using String#split() to split the line in tokens. Example for the separator , :

String attributeNames[] = input.split(",");
JosEduSol
  • 5,268
  • 3
  • 23
  • 31
0

The best way is using:

 String splittedString[] = input.split("the separator");

It's recommended by Oracle.

Super Hornet
  • 2,839
  • 5
  • 27
  • 55
0

Are you just trying to get tokens from the first line? If so, you don't need the while loop at all. Just remove the while { from the beginning and break; } from the end.

Dima
  • 39,570
  • 6
  • 44
  • 70