我们的应用程序中有一个问题可以简化为以下代码:
public static void main(String[] args) throws IOException, ClassNotFoundException {
File tempFile = File.createTempFile("teststream", "");
FileOutputStream fos = new FileOutputStream(tempFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeInt(1);
oos.writeObject("foo");
oos.writeInt(2);
oos.flush();
oos.close();
FileInputStream fis = new FileInputStream(tempFile);
ObjectInputStream ois = new ObjectInputStream(fis);
int n1 = ois.readInt();
Object o1 = ois.readObject();
int n2 = ois.readInt();
}
此代码有效,但如果您注释以下行:
Object o1 = ois.readObject();
下面一行
int n2 = ois.readInt();
将抛出 EOFException
尽管我的文件中有数据,因为我在其中写入了一个对象和一个整数。 javadoc of readInt不表示此行为。我有点担心这个 EOFException
,因为我们想在我们的代码中区分一个真正的 there nothing more to read in your file 异常和一个 < em>内容类型错误一个。
异常的堆栈跟踪是
Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readInt(DataInputStream.java:392)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(ObjectInputStream.java:2793)
at java.io.ObjectInputStream.readInt(ObjectInputStream.java:968)
这意味着DataInputStream
中的以下代码抛出异常:
public final int readInt() throws IOException {
int ch1 = in.read();
int ch2 = in.read();
int ch3 = in.read();
int ch4 = in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
但是当输入流中有数据时,in.read()
不应该返回负数,所以我真的很感兴趣。
是否可以在我的代码中做一些事情来防止这种情况发生(知道我们可能会在某个时候调用 readInd
,其中使用了 writeObject
)?
我正在使用这个版本的 java:
java version "1.7.0_07"
OpenJDK Runtime Environment (IcedTea7 2.3.2) (ArchLinux build 7.u7_2.3.2-2-x86_64)
OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode)
最佳答案
底层流以 block 的形式写入,带有 block 头。当您在写入对象时尝试 readInt
时发现错误的 block 类型并且 in.read()
返回 -1。
下面的方法被调用。
/**
* Attempts to read in the next block data header (if any). If
* canBlock is false and a full header cannot be read without possibly
* blocking, returns HEADER_BLOCKED, else if the next element in the
* stream is a block data header, returns the block data length
* specified by the header, else returns -1.
*/
private int readBlockHeader(boolean canBlock) throws IOException {
// code deleted
int tc = in.peek();
switch (tc) {
case TC_BLOCKDATA:
// code deleted
default:
if (tc >= 0 && (tc < TC_BASE || tc > TC_MAX)) {
throw new StreamCorruptedException(
String.format("invalid type code: %02X",
tc));
}
return -1;
}
当 StreamCorruptedException
在这里可能是更好的选择时,-1 表示已经到达终点。
关于java - 即使文件中仍有数据,ObjectOutputStream.readInt() 也会抛出 EOFException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12598190/