我正在测试 ObjectInputStream
和 ObjectOutputStream
类
尝试在缓冲流对象中扭曲两者..
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/