java - 打开缓冲对象流时出现 EOFException

标签 java buffer objectinputstream objectoutputstream

我正在测试 ObjectInputStreamObjectOutputStream
尝试在缓冲流对象中扭曲两者..

File file = new File("file.lel"); //Assuming the file exist and has data stored in it.   
//will truncate file   
try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));   
 ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file))) //Bad Practice!  
) {   
SomeObject writeMe = new SomeObject(1, 2, 3, 50.5, 'k'); //Object with 3 ints, a double and a char    
final double D = 30.3; //for testing   

out.writeDouble(D);  
out.writeObject(writeMe);   
out.flush();   

double DAgain = in.readDouble();   
SomeObject readMe = (SomeObject)in.readObject();   
readMe.printInfo();   
}   

//Some catch blocks...

但我在上面代码的第 3 行收到 EOFException

Exception in thread "main" java.io.EOFException //header loaded first .. ?!
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)

当我删除缓冲流对象时,代码起作用了..即

try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
 ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))
) { ... }

为什么会出现这种行为?有什么想法吗?

最佳答案

首先,不要这样做。在文件中获得数据之前,不要尝试初始化输入流。

至于为什么它在不缓冲时起作用,我相信问题出在输出流的缓冲上......在缓冲版本中,您正在创建 FileOutputStream这将截断文件,然后将其包装在 BufferedOutputStream 中,然后将其包装在 ObjectOutputStream 中。其中最后一个会将前导码数据写入流中 - 但它只能到达 BufferedOutputStream它缓冲数据。当您尝试创建ObjectInputStream时从文件中读取时,它正在尝试读取序言...但没有任何内容可读取。

您可以轻松地演示这一点:

import java.io.*;

class Test {
    public static void main(String[] args) throws IOException {
        // Not disposing of any resources just for simplicity.
        // You wouldn't actually use code like this!
        FileOutputStream fos = new FileOutputStream("data");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        // Flush the preamble to disk
        bos.flush();

        FileInputStream fis = new FileInputStream("data");
        ObjectInputStream ois = new ObjectInputStream(fis);
    }
}

没有flush()调用,您会得到您所见过的异常​​ - 有了它,没有异常。

正如我所说,在我看来,你一开始就不应该这样做。

关于java - 打开缓冲对象流时出现 EOFException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32196428/

相关文章:

java println ("a==b"+"is"+a==b) 打印 false 而不是 "a==b is true"

java - 使用外部电子邮件应用程序通过电子邮件发送文本输入 android

java - readObject 挂起应用程序

python - 如何使用输出缓冲控制?

java - 我在 ObjectStream 中的以下写作和阅读出了什么问题

java.io.EOFException while writing and read from a servlet

java - 不能从静态上下文中引用的非静态变量

java - http响应中断的字符串? - Java, Android 3.0 平台

java - 尝试使用ZipInputStream解压缩String值时,获取IOException推回缓冲区已满

c - 将文件加载到 RAM(静态)以缩短读取时间