多数のオブジェクトをストリームに入れ、そこからバイト配列を取得して、すべてを読み戻します。最初の 2 つのデータは良好な状態で到着し、次にゼロが返され、次に 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)