1

DataInputStreamファイルから読み取るストリームであるいくつかの単純なクラスがあります。

このストリームをEOFExceptiontry-catch ブロックで囲みました。

時々、読み取ったテキストに EOFException をスローすることがあります。

コンソールへの出力:

"The vessel was in as good condition as I am, and as, I hope
you ar#End of streame#, M. Morrel, and this day and a half was lost from
pure whim, for the pleasure of going ashore, and nothing
else."

この奇妙な動作の原因がわかりませんでした...

コード スニペットは次のとおりです。

public class FormattedMemoryInput {    
    public static void main(String[] args) throws IOException {
        boolean done = false;    
        try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(
                BufferedInputFile.read("./gutenberg/cristo.txt").getBytes()));) {

            while (!done) {
                System.out.print((char) in.readByte());
            }
        } catch (EOFException e) {
            System.err.println("#End of stream#");
        }
    }
} 

静的メソッドBufferedInputFile.read()を使用して最初の 500 行を読み取ります。

public class BufferedInputFile {

    // Throw exceptions to console:
    public static String read(String filename) throws IOException {

        // Reading input by lines:
        BufferedReader in = new BufferedReader(new FileReader(filename));
        StringBuilder sb = new StringBuilder();
        String s;
        int i = 0;

        while ((s = in.readLine()) != null && (i < 500)) {
            sb.append(s + "\n");
            i++;
        }

        in.close();
        return sb.toString();
    }
  • EOFException がテキストにスローされるのはなぜですか?

解決:

それは1行を追加することでした:

while (!done) {
    System.out.print((char) in.readByte());
    System.out.flush(); // this one
}
4

2 に答える 2

2

永遠に読んでいるEOFExceptionからです - の値を変更することはありませんdone

テキストの最後ではなく途中に表示されているのはSystem.err、例外的なケースでSystem.out印刷し、本文を印刷するために使用しているためです。これらは別々のストリームであり、別々にフラッシュされます。System.outに書き込む前にフラッシュするSystem.errと、エラー メッセージの前に本文が表示されると思います。(自動的にフラッシュするprintlnonを使用していることに注意してください。ただし、オンではありません。)System.errprintSystem.out

コードについて変更したいことが他にもさまざまあります。特に、String.getBytes()エンコーディングを指定せずに を使用する場合などです。ただし、質問を正しく理解していると仮定すると、ストリームの違いがあなたが探している理由です。

于 2013-12-22T10:11:04.317 に答える
1

System.outデフォルトでバッファリングされます。System.errそうではありません。プログラムまたはシェルから出力ストリームの 1 つをリダイレクトすると、期待どおりの順序で出力が表示されるはずです。System.outを呼び出すことで、その出力を強制的に印刷できSystem.out.flush();ます。whileループの最後に挿入してみてください。

于 2013-12-22T10:10:51.450 に答える