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被抛出到文本中?

解决方案:

它是在添加一行:

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.err,它会自动刷新,但只是printon System.out,不会。)

关于代码,我还有很多其他的事情要改变——特别是在String.getBytes()没有指定编码的情况下使用——但假设我已经正确理解了你的问题,流中的差异就是你正在寻找的原因。

于 2013-12-22T10:11:04.317 回答
1

System.out默认缓冲;System.err不是。如果您在程序中或从 shell 中重定向输出流之一,您应该会按预期顺序看到输出。System.out您可以通过调用强制打印其输出System.out.flush();while尝试在循环的末尾插入它。

于 2013-12-22T10:10:51.450 回答