我将一些对象放入流中,然后从中取出字节数组,然后读回所有内容。前两条数据完好无损,然后我得到零,然后是 EOF 异常。为什么?
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject("abcdef");
objectOutputStream.writeInt(1);
objectOutputStream.writeObject(new byte[]{1,2,3,4,5,6,7,8});
objectOutputStream.writeInt(2);
objectOutputStream.writeObject(new byte[]{11,12,13,14,15,16,17,18});
objectOutputStream.close();
byte[] original = byteArrayOutputStream.toByteArray();
System.out.println(Arrays.toString(original));
byte[] b=new byte[8];
ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(original));
String s= (String) objectInputStream.readObject(); // works fine
objectInputStream.readInt(); // works fine
objectInputStream.read(b); // why it reads zeroes instead of [1,2,3,4,5,6,7,8]?
System.out.println(Arrays.toString(b));
int length = objectInputStream.readInt(); // EOF unexpectedly reached, why?
objectInputStream.read(b);
}
catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
例外:
java.io.EOFException
at java.io.DataInputStream.readInt(DataInputStream.java:375)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(ObjectInputStream.java:2775)
at java.io.ObjectInputStream.readInt(ObjectInputStream.java:949)