5

I have a large file (English Wikipedia articles only database as XML files). I am reading one character at a time using BufferedReader. The pseudocode is:

file = BufferedReader...

while (file.ready())
    character = file.read()

Is this actually valid? Or will ready just return false when it is waiting for the HDD to return data and not actually when the EOF has been reached? I tried to use if (file.read() == -1) but seemed to run into an infinite loop that I literally could not find.

I am just wondering if it is reading the whole file as my statistics say 444,380 Wikipedia pages have been read but I thought there were many more articles.

4

2 に答える 2

10

このReader.ready()メソッドは、ファイルの終わりをテストするために使用することを意図していません。むしろ、呼び出しread()がブロックされるかどうかをテストする方法です。

EOF に到達したことを検出する正しい方法は、read呼び出しの結果を調べることです。

たとえば、一度に文字を読み取っている場合、read()メソッドはint、有効な文字であるか-1、ファイルの終わりに達した場合に を返します。したがって、コードは次のようになります。

int character;
while ((character = file.read()) != -1) {
    ...
}
于 2010-12-28T06:46:13.890 に答える
2

これは、入力全体の読み取りを保証するものではありません。 ready()基になるストリームにコンテンツの準備ができているかどうかを示すだけです。たとえば、ネットワーク ソケットまたはファイルを介して抽象化している場合は、バッファリングされたデータがまだ利用できないことを意味する可能性があります。

于 2010-12-28T04:59:42.343 に答える