views:

482

answers:

1

I'm confused. I'm trying to loop though 2 files looking at the first token in every line of the first file and comparing it to the third token of every line of the second file. Here is the logical structure in the form of a nested while loop:

BufferedReader reader1 = new BufferedReader(new InputStreamReader(new FileInputStream(fromFile1)));

BufferedReader reader2 = new BufferedReader(new InputStreamReader(new FileInputStream(fromFile2),"EUC-JP"));

String line1, line2 = null;
String temp1, temp2 = null;

while ((line1=reader1.readLine()) != null)
{
    StringTokenizer st1 = new StringTokenizer(line1);
    temp1 = "U"+st1.nextToken();
    while((line2=reader2.readLine()) != null)
    {
        StringTokenizer st2 = new StringTokenizer(line2);
        temp2 = st2.nextToken();
        temp2 = st2.nextToken();
        temp2 = st2.nextToken();
        if(temp2.equals(temp1));
        {
            System.out.println(temp1+" "+temp2);
        }
    }
}

However, all I see in the output is the first token from the first line of the first file and the third token from every line of the second file repeated 6,000 (the length of file 2) times regardless of whether they were "equal" or not. Does this have to do with their different encodings? I can see that having an effect on the equals test, but why isn't the loop behaving properly?

Cheers, Brandon

+3  A: 

it's the ; behind the if

if(temp2.equals(temp1));

But it wouldn't probably work anyway as expected, since you must reopen file 2 within the outer loop, otherwise it will only work correctly for the first line of file 1

ammoQ
Ah, thanks ammoQ that fixed everything. I'm relatively new to file io in java. Why do I have to open the file within the outer loop?
Brandon
Brandon: Because after the first time you run through the inner loop, reader2 is already at the end of the stream; so next time you come to the inner while loop, readLine() will only return null. The simplest (though probably not fastest) way around that is to close and reopen the streamreader.
ammoQ
Ah, of course. Thanks again!
Brandon