打开缓冲对象流时出现 EOFException

EOFException on opening a buffered object stream

我正在测试 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))
) { ... }

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

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

至于为什么它在你不缓冲时工作,我相信问题出在 output 流的缓冲上......在缓冲版本中,你是创建将截断文件的 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() 调用,您会得到您所看到的异常 - 有了 ,没有异常。

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