首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >EOFException的奇怪行为

EOFException的奇怪行为
EN

Stack Overflow用户
提问于 2013-12-22 10:07:27
回答 1查看 111关注 0票数 1

我有一些简单的类,即从文件中读取的DataInputStream流。

我已经用EOFException试捕块包围了这条流。

它有一些奇怪的行为,因为有时它会将EOFException抛到被读取的文本中。

输出到控制台:

代码语言:javascript
复制
"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."

我不知道是什么导致了这种奇怪的行为..。

下面是代码片段:

代码语言:javascript
复制
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行:

代码语言:javascript
复制
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被抛到文本中?

解决方案:

它是在增加一行:

代码语言:javascript
复制
while (!done) {
    System.out.print((char) in.readByte());
    System.out.flush(); // this one
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-22 10:10:51

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20728248

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档