从每次迭代的第一行开始

start from first line in each iteration

我正在阅读两个文件。我的代码如下:

BufferedReader comone = new BufferedReader(new FileReader("G:\xml_one.txt"));
BufferedReader comtwo = new BufferedReader(new FileReader("G:\xml_two.txt"));

int a = 0;          
String one;
String two;

while ((one = comone.readLine()) != null) { 

        a= -111111;
        while ((two = comtwo.readLine()) != null) { 


        if(one.equals(two) == false)
            {
                a =1;
            }
        else
            {
                a=0;
                break;

            }               
        }

        if(a==1)
        {   
            System.out.println("Check this name : "+one);
        }   
    }

在我的代码中,我读取了两个文件。但问题是我想每次都从第一行读取第二个文件(在第二次)。但目前我的代码在第一次迭代中读取第一行,而不是在第二次迭代中再次从第二行开始。我也想在第二行从第一行读取,这意味着在每次迭代(第二个文件)中。

您可以标记 comtwo 的开头,然后在第二次之后调用 comtwo.reset(),这样您会得到如下内容:

while ((one = comone.readLine()) != null) { 

    a= -111111;
    comtwo.mark(someInt); // basically just the length you expect to read in comtwo
    while ((two = comtwo.readLine()) != null) { 


    if(one.equals(two) == false)
        {
            a =1;
        }
    else
        {
            a=0;
            break;

        }               
    }
    comtwo.reset();

    if(a==1)
    {   
        System.out.println("Check this name : "+one);
    }   
}

这应该 return 你的 BufferedReader 达到目标,a.k.a。第一行,循环之后。

Eran 的回答也可行,但这会导致每次迭代都进行文件打开操作,从而产生 IO 开销。而 mark 只会产生内存开销。